2013-07-22 50 views
0

我使用的是實體框架代碼,第一個5與流暢的映射API。 我有一個名爲「實體」一個法定的繼承權表3列實體框架設置使用列名的主鍵

ENTITY1_ID int 
ENTITY2_ID int 
LEVEL int 

關聯模型

public class ENTITY 
{ 
    public virtual ENTITY1 ENTITY1 {get; set;} 
    public virtual ENTITY2 ENTITY2 {get; set;} 
    public virtual int LEVEL {get; set;} 
} 

其中ENTITY1_ID和ENTITY2_ID是走向兩個表的外鍵。 在映射代碼中,我成功了,而不需要增加相關的屬性,以實體類的聲明外鍵:

this.HasRequired(t => t.ENTITY1).WithMany().Map(m => m.MapKey("ENTITY1_ID")); 
this.HasRequired(t => t.ENTITY2).WithMany().Map(m => m.MapKey("ENTITY2_ID")); 

所以我只用列名需要設置主鍵。使用類似:

this.HasKey(new {"ENTITY1_ID", "ENTITY2_ID"}); 

我想這樣做,以避免污染我的模型與持久性相關的屬性(IDS ..)。 有沒有可能在Entity Framework 5上做到這一點?

回答

-1

如果這是一個多對多的表,那麼你可以用單獨的屬性創建這個(無需流利的映射)

public class Entity1 
{ 
    public class Id { get; set; } 
    // Other properties 
} 

public class Entity2 
{ 
    public class Id { get; set; } 
    // Other properties 
} 

這裏是連接表

public class EntityEntity 
{ 
    [Key] 
    [Column(Order = 1)] 
    public int Entity1Id {get;set;} 

    [Key] 
    [Column(Order = 2)] 
    public int Entity2Id {get;set;} 

    public int Level {get; set;} 

    public virtual Entity1 Entity1 {get; set;} 
    public virtual Entity2 Entity2 {get; set;} 
} 

也就是說一切你需要的。其餘的'魔術'是爲你完成的。

記住這些添加到您的DbContext

public class DataContext : DbContext 
{ 
    public DbSet<Entity1> Entity1s {get; set;} 
    public DbSet<Entity2> Entity2s {get; set;} 

    public DbSet<EntityEntity> EntityEntities {get; set;}   
} 
+0

請閱讀carefuly我的問題,我不想申報Entity1Id和Entity2Id。 – enenkey