5

非常簡單,我首先使用Entity Framework 4.1代碼,而我想用modelBuilder上的流利調用替換我的[ForeignKey(..)]屬性。類似於下面的WithRequired(..)和HasForeignKey(..),它將顯式外鍵屬性(CreatedBySessionId)與關聯的導航屬性(CreatedBySession)綁定在一起。但我想這樣做一對一的relationshipip而不是一對多:EF 4.1 Code First ModelBuilder HasForeignKey一對一關係

modelBuilder.Entity<..>().HasMany(..).WithRequired(x => x.CreatedBySession).HasForeignKey(x => x.CreatedBySessionId) 

更具體的例子如下。這對於[ForeignKey(..)]屬性來說相當愉快,但我希望取消它並僅在modelbuilder上對其進行配置。

public class VendorApplication 
{ 
    public int VendorApplicationId { get; set; } 

    public int CreatedBySessionId { get; set; } 
    public virtual Session CreatedBySession { get; set; } 
} 

public class Session 
{ 
    public int SessionId { get; set; } 

    [ForeignKey("CurrentApplication")] 
    public int? CurrentApplicationId { get; set; } 
    public virtual VendorApplication CurrentApplication { get; set; } 

    public virtual ICollection<VendorApplication> Applications { get; set; } 
} 

public class MyDataContext: DbContext 
{ 
    public IDbSet<VendorApplication> Applications { get; set; } 
    public IDbSet<Session> Sessions { get; set; } 

    protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
     modelBuilder.Entity<Session>().HasMany(x => x.Applications).WithRequired(x => x.CreatedBySession).HasForeignKey(x => x.CreatedBySessionId).WillCascadeOnDelete(false); 
     // Note: We have to turn off Cascade delete on Session <-> VendorApplication relationship so that SQL doesn't complain about cyclic cascading deletes 
    } 
} 

這裏會話可以負責創造了許多VendorApplications(Session.Applications),但會話最多是一個VendorApplication在同一時間(Session.CurrentApplication)工作。我想將currentApplicationId屬性與modelBuilder中的CurrentApplication導航屬性綁定,而不是通過[ForeignKey(..)]屬性。

事情我已經試過

當您刪除[ForeignKey的(..)]屬性CurrentApplication屬性,其中不依賴於CurrentApplicationId列的數據庫生成CurrentApplication_VendorApplicationId列。

我試着明確映射使用CurrentApplicationId列名,如下的關係,但顯然因爲數據庫列名「CurrentApplicationId」已被使用由酒店Session.CurrentApplicationId這會產生一個錯誤:

modelBuilder.Entity<Session>().HasOptional(x => x.CurrentApplication).WithOptionalDependent().Map(config => config.MapKey("CurrentApplicationId")); 

感覺就像我錯過了一些非常明顯的東西,因爲我想要做的就是執行與[ForeignKey(..)]相同的操作,但在模型構建器中。或者這是一種糟糕的做法,並被明確排除?

回答

10

您需要將關係映射爲一對多並省略關係中的集合屬性。

modelBuilder.Entity<Session>() 
    .HasOptional(x => x.CurrentApplication) 
    .WithMany() 
    .HasForeignKey(x => x.CurrentApplicationId) 
+1

是的就是這樣!我之前實際上已經使用過這個配置,但是EF提出了一個多重衝突的例外,所以我確定這個關係必須是1:1。當然,現在我意識到實際上發生了多重衝突,因爲我最初的CurrentApplicationId是不可空的... **(face palm)**。感謝您的幫助,非常感謝! – Walter 2012-07-14 03:38:22

相關問題