2014-01-08 83 views
0

我有一個包含像這樣訪問父實體從孩子實體框架

public class Device 
{ 
    [Key] 
    [DatabaseGenerated(DatabaseGeneratedOption.None)] 
    public long DeviceSerial { get; set; } 

    public virtual ICollection<DeviceLogEntry> Errors { get; set; } 
} 

這工作得很好DeviceErrorLog設置列表的父實體Device,但我希望能夠給內DeviceLogEntry從訪問Device所以我增加了以下內容:

public class DeviceLogEntry 
{   
    [Key] 
    public int Id { get; set; } 

    public virtual Device Device { get; set; } 
} 

現在的DeviceLogEntry表我的數據庫結構與Device相關的3列:[Device_DeviceSerial],[Device_DeviceSerial1],[Device_DeviceSerial2]

我錯過了防​​止這種情況的鏈接或一段代碼嗎?

更新

我已經更新了代碼,包括設備作爲已經刪除了一個額外的列,但我仍然似乎有一個太多[Device_DeviceSerial],[Device_DeviceSerial1]

public class DeviceLogEntry 
{   
    [Key, Column(Order = 0)] 
    public int Id { get; set; } 

    [Key, Column(Order = 1)] 
    [ForeignKey("Device")] 
    public long DeviceSerial { get; set; } 
} 
+0

@Adriano你是什麼意思呢?它是一個POCO我認爲 – Chris

+0

'Device'是否有一個名爲'DeviceSerial'的屬性? –

+0

@Guillelon是的,請參閱更新 – Chris

回答

2

您重新嘗試的外鍵來模擬一對多的關係。子實體在數據庫中需要一個外鍵給父母的ID,但是你沒有遵循命名約定,所以EF不知道他們正在建模相同的關係,併爲'DeviceSerial'屬性添加了獨立的列,'Errors'屬性和'設備'屬性。試試這個:

public class Device 
{ 
    //You need the Key annotation because the name does not follow the 
    //convention for a Key 
    //if you'd called it "DeviceID" or "ID" then you wouldn't need it 
    [Key] 
    //EF defaults int keys to Identity 
    //assuming longs are the same you need this annotation to stop that 
    [DatabaseGenerated(DatabaseGeneratedOption.None)] 
    public long DeviceSerial { get; set; } 

    //This is a navigation property. 
    //The virtual keyword lets EF override the method in a proxy class 
    //so that it can support lazy loading. 
    //Convention would name it "DeviceLogEntries" 
    public virtual ICollection<DeviceLogEntry> Errors { get; set; } 
} 

public class DeviceLogEntry 
{   
    //You don't need the Key annotation 
    public int Id { get; set; }   

    //You don't have to include the foreign key AND the navigation property 
    //in the entity but life is probably easier if you do... 
    public long DeviceSerial { get; set; } 

    //...so I would add the navigation property to your entity 
    //Foreign key doesn't follow convention (it's not "DeviceID") 
    //so you need to tell it what it is 
    [ForeignKey("DeviceSerial")] 
    //And again if the navigation property in the parent had been named 
    //"DeviceLogEntries" then you wouldn't need to tell EF that the 
    //inverse navigation property is actually called "Errors" 
    [InverseProperty("Errors")] 
    public virtual Device Device {get;set;) 
} 

參考文獻:

Code First Data Annotations

Making Do with Absent Foreign Keys

+0

謝謝你,我已經偶然發現了這個問題之前正確的答案,但你的解釋是偉大的,我學到了一些東西 – Chris