2012-03-28 62 views
0

我的代碼像下面實體框架4.3.1如何創建關聯

public class User 
{ 
    public int ID { get; set; } 
    public int BillingAddressID { get; set; } 
    public Address BillingAddress { get; set; } 
    public IList<Shipment> Shipments { get; set; } 
} 

public class Address 
{ 
    public int ID { get; set; } 
    public string Street { get; set; } 
    public string City { get; set; } 
    public string ZipCode { get; set; } 
} 

public class Shipment 
{ 
    public int ID { get; set; } 
    public string State { get; set; } 
    public int DeliveryAddressID { get; set; } 
    public Address DeliveryAddress { get; set; } 
    public User ShipUser { get; set; } 
    //[ForeignKey("ShipUser")] 
    public int ShipUserID { get; set; } 
    //public int UserId { get; set; } 
} 

public class TestContext : DbContext 
{ 
    public DbSet<User> Users { get; set; } 
    public DbSet<Address> Addresses { get; set; } 
    public DbSet<Shipment> Shipments { get; set; } 

    protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
     modelBuilder.Entity<Shipment>().HasRequired(u => u.ShipUser) 
      .WithMany(d => d.Shipments) 
      .HasForeignKey(c => c.ShipUserID) 
      .WillCascadeOnDelete(false); 
    } 
} 
  1. 如果我刪除重寫方法,我會得到一個錯誤「SQLEXCEPTION:引進國外KEY約束‘FK_Shipments_Users_ShipUserID’上表'Shipments'可能會導致循環或多個級聯路徑,指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY約束 無法創建約束,請參閱前面的錯誤。
  2. 如果我刪除Shipment類中的ShipUserID,它將正常工作,當我看到由ef創建的表時,我在表Shipment中找到一個名爲Shipment_UserID的列。我不知道爲什麼。
  3. 如果將類indenty鍵重命名爲UserID,它也可以正常工作。

無論如何我都試過,但我不知道原因,我需要一些關於EF協會的書籍。

回答

0
  1. 如果沒有沒有cascadeDelete =假指定的映射爲一個關係,它會創建多個級聯路徑,如果你從Shipment有拖關係,user。 按照慣例,你可以使用公共

    Public User ShipUser { get; set; }
    public int ShipUserID { get; set; }

它將使用ShipUserID按約定外鍵。

  1. 如果刪除ShipUserID Ef需要創建自己的外鍵來保持關係。那是你的'Shipment_UserID'

  2. rename the class indenty key to UserID我不明白你的意思。

Here is a good tutorial下手