我想动态地创建我的数据模型来处理一些现有的类和一个自定义的XML映射文件,因为我有很多现有的表和大量现有的业务类(也许疯狂,不知道)。EF4.1的动态流利映射
对于使用不同列名称或与现有列不相对应的属性,我想调用.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]]'.
谢谢,就是这样。你能帮我调用.HasColumnName()吗?这很难,因为.Property有很多覆盖,我不知道如何调用正确的。 – powlette 2012-03-19 17:23:29
当然,我在上面。 – 2012-03-19 17:49:33