知其然不知其所以然的悲慘后果【EF CodeFirst 實體關系兩日游】


先上測試代碼

    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、去掉OnModelCreating重載方法

  報錯:

SqlException: Introducing FOREIGN KEY constraint 'FK_Shipments_Users_ShipUserID' on table 'Shipments' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint. See previous errors.

 分析原因:EF創建的FK默認是帶級聯的

  

  因為SqlServer並不是真正運行去校驗是否循環或多重級聯,而是通過一個級聯路徑(可能與Name有關系)

  如果主鍵列不叫ID,也沒有問題,但這樣EF在建庫時,會自動創建一列外鍵列(如ShipUser_UserID在代碼中看不到)




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM