我知道这个问题很老,但我在任何地方都找不到我的场景的明确说明。
我只是在不会创建数据库的配置和创建数据库但不会保存实体的配置模型之间来回切换!
当然,您现在报告的例外是最令人恼火的例外之一!
您可能有发现问题。我需要查看更多您的模型,以帮助您确定问题出在哪里。
“Namespace.MyEntity”是什么样的?它是否参与了 TPT 继承映射策略?
如果是这样,您是否与其他 TPT 实体有任何 1|1 关系(<--不太可能)或 1|* 关系?
我在这里完全是在猜测,但这需要反复试验才能弄清楚,所以我会发布它以帮助任何搜索您的错误和 [-- TPT | 每种类型的表 | 必填 | 关系 | 家长 | 儿童 | 共享 | 基地 | 抽象的 - ]
在我的场景中,当我需要 modelBuilder.Entity().HasRequired(x => x.TPT_Derived_Parent_Class).WithOptional(); 我被迫让 TPT_Derived_Child_Class 从一个单独的项目基类继承而不是 TPT_Derived_Parent_Class
我发现,在我的解决方案中,当您的 TPT 派生类具有引用从不同 TPT 父类派生的类的不可空字段时,Code First 以正确的顺序发现实体非常重要
当我将 TPT 用于派生(二级)基类和派生自第二级基类之间需要外键关系。
例如,这对我不起作用:
public abstract ProjectBaseClass : IProjectBase
{
[Key]
public int ProjectClassesId {get;set;}
}
[Table("TPT_BaseClass1")]
public abstract TPT_Specialized_Base_Class1 : ProjectBaseClass
{
//...specialized stuff in here
}
[Table("TPT_BaseClass2")]
public abstract TPT_Specialized_Base_Class2: ProjectBaseClass
{
//...specialized stuff in here
}
[Table("ConcreteChild")]
public TPT_Child_Concrete_Class : TPT_Specialized_Base_Class1
{
public int TPT_Parent_Concrete_Class_KeyId {get;set;};
[ForeignKey("TPT_Parent_Concrete_Class_KeyId ")]
TPT_Parent_Concrete_Class ParentSpecializedClass {get;set;};
}
[Table("ConcreteParent")]
public TPT_Parent_Concrete_Class : TPT_Specialized_Base_Class2
{
//optional relationship
public int? TPT_Child_Concrete_Class_KeyId {get;set;};
[ForeignKey("TPT_Child_Concrete_Class_KeyId")]
TPT_Child_Concrete_Class ChildSpecializedClass {get;set;};
}
public projectContext: DbContext
{
public DbSet<TPT_Specialized_Base_Class1>
public DbSet<TPT_Specialized_Base_Class2>
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// There is no configuration I could find that would make the model above work!
// However, if you make each TPT_Specialized_Base_Class inherit from different
// ProjectBaseClass like:
public ProjectBaseClass1 : IProjectBase
public ProjectBaseClass2 : IProjectBase
public TPT_Specialized_Base_Class1 : ProjectBaseClass1 {...}
// and
public TPT_Specialized_Base_Class2 : ProjectBaseClass2 {...}
// or, more sensible...
public TPT_Specialized_Base_Class1 : IProjectBase
// and
public TPT_Specialized_Base_Class2 : IProjectBase
// then you can do the following, making sure you *discover* the child TPT base
// class first
modelBuilder.Entity<TPT_Specialized_Base_Class1>() //this one is inherited by the derived class that has the *required* reference to a TPT derived parent
.Ignore(x => x.PropertyNamedInErrorMessage);
modelBuilder.Entity<TPT_Specialized_Base_Class2>();
.Ignore(x => x.PropertyNamedInErrorMessage);
// when I flipped the order of the classes above, it could not determine the
// principal end of the relationship, had a invalid multiplicity, or just wouldn't
// save...can't really remember what it was crying about...
modelBuilder.Entity<TPT_Child_Concrete_Class>()
.HasRequired(x => x.TPT_Parent_Concrete_Class ).WithOptional();
& ProjectBaseClass2
}
}