通常,當使用實體框架添加條目時,它知道在ID列是身份鍵時忽略該列。但是,出於某種原因,在將關係添加到我的公司類後,每次實體框架嘗試添加新的公司條目時,都會嘗試顯式添加具有0值的標識並失敗。此外,每當我嘗試添加任何具有與公司類關係的類的條目時,都會違反約束條件。實體框架試圖在添加條目時明確添加ID
這是公司類:
public int Id { get; set; }
[Required]
public string Nombre { get; set; }
[ForeignKey("Customer")]
public int CustomerId { get; set; }
[ForeignKey("CompanyType")]
public string CompanyTypeCode{ get; set; }
/* more properties */
public virtual Parameters Parameters { get; set; }
的問題開始了,當我加入了參數虛擬財產的類發生。這是參數類
public int Id { get; set; }
public int CompanyId { get; set; }
/* more stuff */
public virtual Company Company { get; set; }
此外,我不得不定義與流利的API的關係:
modelBuilder.Entity<Company>().HasRequired(e => e.Parameters).WithRequiredDependent(p => p.Company);
這是實體框架試圖執行命令。需要注意的是它試圖明確添加的,而不是忽略它的Id:
INSERT [dbo].[Company]([Id], [Name], [CustomerId], [Code], [POS], [CompanyCode], [VAT], [Path], [ExpiryDate], [CreatedBy], [CreateDate], [UpdatedBy], [UpdateDate])
VALUES (@0, @1, @2, @3, @4, @5, @6, NULL, NULL, @7, @8, @9, @10)
-- @0: '0' (Type = Int32)
-- @1: 'asdasd' (Type = String, Size = -1)
-- @2: '9' (Type = Int32)
-- @3: '20222222223' (Type = String, Size = -1)
-- @4: ' 1' (Type = String, Size = -1)
-- @5: '1' (Type = String, Size = 128)
-- @6: '4' (Type = Int32)
-- @7: '24' (Type = Int32)
-- @8: '11/4/2017 17:46:22' (Type = DateTime2)
-- @9: '24' (Type = Int32)
-- @10: '11/4/2017 17:46:22' (Type = DateTime2)
我刪除了參數上的CompanyId屬性,使Id既是PK又是ForeignKey,並使其成爲委託人,並且它工作正常!謝謝! – Magnus