2015-06-19 28 views
1

我正在使用EntityFrameworkCodeFirst與現有數據庫。我遇到了一些關鍵問題。我創建 四個測試表和模型模擬的情況:EntityFramework代碼首先手動設置作爲FK到其他表的PKs

- 主容器類

public class Party 
{ 
    // Id is generated at database 
    public int Id { get; set; } 

    public virtual ICollection<PartyRole> PartyRoles { get; set; } 
} 

角色類型 - 類型根據角色一些數據分開。

public class RoleType 
{ 
    // This is static library table so need to generate Id 
    public short Id { get; set; } 
    public string Value { get; set; } 
} 

成員角色 - 角色各方

public class PartyRole 
{ 
    // PartyId and RoleTypeId is composite PK 
    public int PartyId { get; set; } // Is FK to Party 
    public short RoleTypeId { get; set; } // Is FK to RoleType 

    public virtual Party Party { get; set; } 
    public virtual RoleType RoleType { get; set; } 
    public virtual ICollection<Insurer> Insurers { get; set; } 
} 

保險

public class Insurer 
{ 
    public int Id { get; set; } 
    // PartyId and RoleTypeId is composite FK to PartyRole 
    public int PartyId { get; set; } 
    public short RoleTypeId { get; set; } 

    // Other properties 

    public virtual PartyRole PartyRole { get; set; } 
} 

我還沒有爲簡單映射的細節。映射細節是正確的,並使用Fluent API編寫。 當我嘗試手動設置成員角色的的PK,並插入這個值是不是保險公司反映:

using (MyTestContext testContext = new MyTestContext()) 
{ 
    Insurer insurer = new Insurer(); 

    PartyRole partyRole = new PartyRole() 
    { 
     PartyId = 1, // Party with this Id already exist 
     RoleTypeId = 1, // RoleType with this id already exist 
     Insurers = new List<Insurer>() { insurer } 
    }; 

    testContext.Set<PartyRole>.Add(partyRole); 
    testContext.SaveChanges(); 
} 

當我執行上面的代碼生成以下SQL語句:

insert into "PARTY_ROLES" 
      ("ID", 
      "ROLE_TYPE_ID") 
values  (1 /* :p0 */, 
      1 /* :p1 */); 

insert into "INSURERS"(
    "PARTY_ID", 
    "ROLE_TYPE_ID") 
values (
    0 /* :p0 */, 
    0 /* :p1 */); 

我的問題是,爲什麼EF發送(0,0)插入INSURERS,他們應該是(1,1)

如果PartyIdRoleTypeIdFKS成員角色模型,將派遣(1,1)

+0

我猜'Insurer.Id'是一個標識列? –

+0

是的,它是一個身份專欄@GertArnold –

+0

你還可以模擬'PartyRole'的構造函數中發生了什麼(如果有的話)? –

回答

0

EF無法猜測這一點。你可以隨時手動設置保險公司的鑰匙:

Insurer insurer = new Insurer() 
{ 
    PartyId = 1, 
    RoleTypeId = 1 
}; 
... 
testContext.SaveChanges(); 
相關問題