我有一个具有以下架构的表:
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)