知其然不知其所以然的悲惨后果【EF CodeFirst 实体关系两日游】
生活随笔
收集整理的這篇文章主要介紹了
知其然不知其所以然的悲惨后果【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在代碼中看不到)
轉載于:https://www.cnblogs.com/wangcl/archive/2012/03/27/2419943.html
總結
以上是生活随笔為你收集整理的知其然不知其所以然的悲惨后果【EF CodeFirst 实体关系两日游】的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: EIGRP Metric计算
- 下一篇: POJ 3635 Full Tank?