在我的数据库中,我创建了一个类似于此的表:
dbo.Words
WordId INT PRIMARY KEY
WordText NVARCHAR(75)
WordTypeId INT FK
WordTypeId引用另一个查找表。它将具有以下值之一:
Verb
Noun
Adjective
我想创建像这样的实体类:
public class Word
{ ... }
public class Noun : Word
{ ... }
public class Verb : Word
{ ... }
public class WordType
{ ... }
public class MyContext : DbContext
{
public DbSet<Noun> Nouns { get; set; }
public DbSet<Verb> Verbs { get; set; }
public DbSet<Word> Words { get; set; }
public DbSet<WordType> WordTypes { get; set; }
}
我将如何在Entity Framework 4.1中实现这一目标 - 代码优先? 当我查询名词DbSet时,我希望它只返回带有WordTypeId的单词,而不管我的名词类型在WordTypes表中是什么。
答案 0 :(得分:10)
您需要采用每个层次结构表(TPH),其中整个层次结构映射到包含所有类的所有属性的单个数据库表(dbo.Words
),并使用WordTypeId
列作为Discriminator专栏......你走了。
<强> 1。域模型
public abstract class Word
{
public int WordId { get; set; }
public string WordText { get; set; }
//DO NOT map the WordTypeId column
//as it is used as the Discriminator column
}
public class Noun : Word { }
public class Verb : Word { }
public class Adjective : Word { }
<强> 2。上下文强>
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//Assuming WordTypeId eqauls 1 for Nouns, 2 for Verbs, 3 for Adjectives
modelBuilder.Entity<Noun>().Map<Word>(c => c.Requires("WordTypeId").HasValue(1));
modelBuilder.Entity<Verb>().Map<Word>(c => c.Requires("WordTypeId").HasValue(2));
modelBuilder.Entity<Adjective>().Map<Word>(c => c.Requires("WordTypeId").HasValue(3));
}
要使用动词:
var verbs = x.Words.OfType<Verb>()