问题描述
我正在尝试模拟我从第三方库中的具体基类继承,然后使用Entity Framework Code First映射我自己的类的场景。我更希望我的类具有与基类相同的简单名称。我显然不能更改基类的类名,也不能将基类更改为抽象。正如预期的那样,我收到以下错误:
I'm attempting to simulate a scenario in which I am inheriting from concrete base classes in a 3rd party library, then mapping my own classes using Entity Framework Code First. I would really prefer for my classes to have the same simple name as the base classes. I obviously can't change the class names of the base classes, nor can I change the base class to abstract. As expected, I get the following error:
据我所知,在EF6中,只要实际映射了其中一个类,这是可能的。但是,如果我尝试使用fluent API忽略基类,则会收到以下错误:
As I understand it, in EF6 this is possible so long as only one of the classes is actually mapped. However, if I attempt to ignore the base class using the fluent API, I get the following error instead:
...这似乎表明通过忽略基类,我也忽略了任何子类。完整代码如下。有什么方法可以解决这个问题并且unignore这个子类?或者这是EF类型映射的限制吗?
... which seems to indicate that by ignoring the base class, I ignore any subclasses as well. Full code below. Any way to work around this and "unignore" the subclass? Or is this a limitation of EF type mapping?
namespace EfInheritanceTest.Models.Base
{
public class Order
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual decimal Amount { get; set; }
}
}
namespace EfInheritanceTest.Models
{
public class Order : Base.Order
{
public virtual DateTime OrderDate { get; set; }
}
}
namespace EfInheritanceTest.Data
{
public class OrdersDbContext : DbContext
{
public OrdersDbContext() : base ("OrdersDbContext") { }
public IDbSet<EfInheritanceTest.Models.Order> Orders { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Types<Models.Base.Order>().Configure(c => c.Ignore());
modelBuilder.Types<Models.Order>().Configure(c => c.ToTable("order"));
modelBuilder.Entity<Models.Order>().Map(c =>
{
c.MapInheritedProperties();
c.ToTable("order");
});
}
}
}
推荐答案
反正有点晚了:我能够通过非常简单的配置解决问题:
It's a bit late, anyway: I was able to solve the issue with very simple configuration:
modelBuilder.Ignore<MyBaseClass>();
因此,EF根本不关心MyBaseClass,但可以使用MyInheritedClass,因为它不是。完美!
So EF don't care about MyBaseClass at all, but works with MyInheritedClass as it is not. Perfect!
第二个错误与:
modelBuilder.Types<Models.Base.Order>().Configure(c => c.Ignore());
从EF映射中排除这两个类(它排除了Models.Base.Order中的所有层次结构)。
as you excluded both classes from EF mapping (it excludes all hierarchy from Models.Base.Order).
。
这篇关于忽略实体框架代码中的基类型也会忽略子类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!