1

這裏一個簡單的模型流利的映射:出了錯在EF 4.1代碼第一次

public class Product1 
{ 
    public int Id { get; set; } 
    public double Price { get; set; } 
    public int CurrencyID { get; set; } 
    public Currency Currency { get; set; } 
} 

public class Product2 
{ 
    public int Id { get; set; } 
    public double Price { get; set; } 
    public int CurrencyID { get; set; } 
    public Currency Currency { get; set; } 
} 

public class Currency 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public string ISO4217 { get; set; } 
    public string Symbol { get; set; } 
} 

正如你可以看到,貨幣僅僅是將兩個不同的實體使用的名單,但如果我嘗試運行這,它給了我一個錯誤,說這是無效的,因爲可能導致多個層疊路徑。

現在我正在努力思考,如何建模上OnModelCreating

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{ 
    modelBuilder.Entity<Product1>().HasRequired(p => p.Currency).WithMany().WillCascadeOnDelete(false); 
    modelBuilder.Entity<Product2>().HasRequired(p => p.Currency).WithMany().WillCascadeOnDelete(false); 
} 

但由於某些原因這一點,雖然產品被正確創建每當我嘗試加載它,貨幣談到空。

我在這種建模中做錯了什麼?

謝謝!

+0

你可以寫你的評論作爲答案,並接受你自己的答案。閱讀並查看其他人已經解決問題更容易。 – Slauma

+0

我知道,但是因爲我是新來的,所以我不能那樣做,直到我獲得10點聲望點。這是一個愚蠢的規則,但這不是我的錯。 –

回答

1

我想通了,我會在這裏解釋以供將來參考:好看基地創建後,我意識到,這是出於錯誤的領域創造了FK:P1:ID - >貨幣:ID,當正確的應是P1:CurrencyID - >貨幣:ID

於是我找到了一種方法來強制正確的FK:

modelBuilder.Entity<Product1>().HasRequired(p => p.Currency).WithMany().HasForeignKey(p => p.CurrencyId); 

而這一切!

0

地圖你的類是這樣的:

public class Product1Mapping : EntityTypeConfiguration<Product1> 
    { 
    public Product1Mapping() 
     { 
     ToTable("Product1"); 
     HasKey(p => p.Id); 
     HasRequired(p => p.Tag).WithMany().HasForeignKey(t => t.CurrencyID); 
     } 
    } 

    public class Product2Mapping : EntityTypeConfiguration<Product2> 
    { 
     public Product2Mapping() 
     { 
     ToTable("Product2"); 
     HasKey(p => p.Id); 
     HasRequired(p => p.Tag).WithMany().HasForeignKey(t => t.CurrencyID); 
     //other properties 
     } 
    } 

和改變你OnModelCreating製作方法是這樣的:

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
     { 
      base.OnModelCreating(modelBuilder); 
      modelBuilder.Configurations.Add(new AccountMapping()); 
      // Add other mapping classes 
     } 

     public DbSet<Product1> Product1{ get; set; } 
     public DbSet<Product2> Product2{ get; set; } 

看到這些鏈接,瞭解更多信息:

http://msdn.microsoft.com/en-us/data/jj591617.aspx

http://entityframework.codeplex.com/workitem/1049