Fir*_*ead 4 c# entity-framework code-first ef-code-first
这是我正在做的事情、正在发生的事情以及应该发生的事情的通用示例:
首先,我声明我的代码优先模型,如下所示:
语境:
namespace Models {
public class MyContext : DbContext
{
public DbSet<ClassA> ClassA { get; set; }
public DbSet<ClassB> ClassB { get; set; }
public MyContext()
: base("name=MyContext")
{
}
}
}
Run Code Online (Sandbox Code Playgroud)
A 类和 B 类:
namespace Models {
public class ClassA
{
public int ClassAID { get; set; }
public string BaseAVal { get; set; }
public virtual ICollection<ClassB> ClassBChildren {get; set; }//Relation Property
}
public class ClassB
{
public int ClassBID { get; set; }
public int ClassAID { get; set; }//Foreign Key
public string BaseBVal { get; set; }
public virtual ClassA ClassAParent { get; set; }//Relation Property
}
}
Run Code Online (Sandbox Code Playgroud)
现在在其他地方,在另一个命名空间中,我有从模型类派生的用于不同目的的类。
派生类:
namespace CalculatedModels {
public class DerivedClassA : ClassA
{
string SecondAVal { get; set; }
public static DerivedClassA fromDBItem(ClassA dbItem) {
//Create a DerivedClassA
//Copy over inherited properties from dbItem (via Reflection)
//Calculate its non-inherited properties
//return it
}
public ClassA toDBItem() {
//Create a ClassA
//Copy over inherited properties from this (via Reflection)
//return it
}
}
public class DerivedClassB : ClassB
{
string SecondBVal { get; set; }
//Conversion functions similar to those in DerivedClassA go here...
}
}
Run Code Online (Sandbox Code Playgroud)
当我让 EntityFramework 从该模型生成数据库时,问题就出现了。我不希望它包含派生类中的任何内容。它们不是数据库关心的!否则为什么我要把它们放在完全不同的命名空间中,并使上下文中的集合成为非扩展基类型?表格应该如下所示:
Table: ClassA
---Columns---
ClassAID (PrimaryKey, int, not null)
BaseAVal (nvarchar(max), null)
Table: ClassB
---Columns---
ClassBID (PrimaryKey, int, not null)
ClassAID (ForeignKey, int, not null)
BaseBVal (nvarchar(max), null)
Run Code Online (Sandbox Code Playgroud)
但 EF 坚持通过添加派生类新声明的属性来破坏我的预期架构,如下所示:
Table: ClassA
---Columns---
ClassAID (PrimaryKey, int, not null)
BaseAVal (nvarchar(max), null)
SecondAVal (nvarchar(max), null) --This should NOT be here!!
Discriminator (nvarchar(128)) --Neither should this!!
Table: ClassB
---Columns---
ClassBID (PrimaryKey, int, not null)
ClassAID (ForeignKey, int, not null)
BaseBVal (nvarchar(max), null)
SecondBVal (nvarchar(max), null) --This should NOT be here!!
Discriminator (nvarchar(128)) --Neither should this!!
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,它包括派生类作为模型和/或数据库系统的可能部分,尽管模型中没有任何内容与它们有关。他们引用模型中的内容,而不是相反——永远。我不想让它使用它们!我怎样才能阻止它这样做?
实体框架正在做它应该做的事情,因为您的设置遵循每个层次结构表 (TPH) 继承模式。
添加了鉴别器,以便数据库可以区分 ClassA 或 DervivedClassA 何时添加到数据库
您可以使用 NotMapped 属性停止 EF 映射您的派生类。添加以下命名空间
using System.ComponentModel.DataAnnotations.Schema;
Run Code Online (Sandbox Code Playgroud)
派生类B
[NotMapped]
public class DerivedClassB : ClassB
{
string SecondBVal { get; set; }
//Conversion functions similar to those in DerivedClassA go here...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1951 次 |
| 最近记录: |