我想动态创建我的数据模型来处理一些现有的类和一个自定义 XML 映射文件,因为我有很多现有的表和很多现有的业务类(我不知道可能很疯狂)。
对于使用不同列名或不对应于现有列的属性,我想调用 .Ignore() 和 .HasColumnName() 但我想动态地执行此操作。
所以我希望能够进行这样的调用,但我想根据反射和使用 Linq.Expressions 的 XML 配置文件动态地调用它们(我从来没有机会使用过):
modelBuilder.Entity<Product>().Property(p => p.QuantityInStock).HasColumnName("UnitsInStock");
或者
modelBuilder.Entity<Product>().Ignore(p => p.QuantityInStock);
这就是我正在尝试的(最终我将参考我的 XML 映射来确定要映射哪些属性以及要忽略哪些属性):
Type entityType = typeof(Product);
var config = modelBuilder.GetType().GetMethod("Entity")
.MakeGenericMethod(entityType)
.Invoke(modelBuilder, null);
var ignore = config.GetType().GetMethod("Ignore").MakeGenericMethod(entityType);
var paramEx = Expression.Parameter(entityType);
var lambdaEx = Expression.Lambda(Expression.Property(paramEx, "QuantityInStock"), paramEx);
ignore.Invoke(config, new[] { lambdaEx });
但我的 lambda 表达式不正确:
Object of type 'System.Linq.Expressions.Expression`1[System.Func`2[ConsoleApplication2.Product,System.Int16]]'
cannot be converted to type
'System.Linq.Expressions.Expression`1[System.Func`2[ConsoleApplication2.Product,ConsoleApplication2.Product]]'.