小编vam*_*nam的帖子

通过动态创建linq查询在c#中为sql等效项创建linq表达式,用于sql等效项

我有一个具有以下架构的表:

  create table test 
  (
    foo1 nvarchar(4),
    foo2 nvarchar(30)
  )
  create unique index test_foo1 on test (foo1);
Run Code Online (Sandbox Code Playgroud)

当使用EF使用Entity创建实体时,它会生成类似以下的类:

public class Test
{
  public string foo1 {get; set;}
  public string foo2 {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

因此,在编辑此记录时,我将像下面那样构建动态表达式树,以查找是否存在用于实际编辑的数据库记录:

Expression combinedExpression = null;

            foreach (string propertyName in keyColumnNames)
            {
               var propertyInfo = typeof(Entity).GetProperty(propertyName);
               var value = propertyInfo.GetValue(entityWithKeyFieldsPopulated);
               var type = propertyInfo.PropertyType;


                Expression e1 = Expression.Property(pe, propertyName);
                Expression e2 = Expression.Constant(value, type);
                Expression e3 = Expression.Equal(e1, e2);

                if (combinedExpression == null)
                {
                    combinedExpression = e3;
                } …
Run Code Online (Sandbox Code Playgroud)

c# sql linq linq-expressions

5
推荐指数
1
解决办法
134
查看次数

标签 统计

c# ×1

linq ×1

linq-expressions ×1

sql ×1