2015-03-30 112 views
1

我目前有僱員模型添加額外的列連接表

public string FirstName { get; set; } 
public string LastName { get; set; } 
public virtual ICollection<StateLicenseType> Licenses { get; set; } 

和許可證類型型號

public class StateLicenseType 
{ 
    public int StateLicenseTypeId { get; set; } 
    public string State { get; set; } 
    public string LicenseName { get; set; } 
    public virtual Employee Employee { get; set; } 
} 

這種關係可以是一對多的,但我還需要添加一些信息到保存時的許可證。我需要能夠存儲員工的唯一許可證編號,並且無法在四處搜索時瞭解如何執行此操作。有沒有辦法讓Entity Framework向連接表添加一列,然後即使我必須自己更新它?

有沒有更好的/不同的方式來建模與EF的這種關係?

在一箇舊的數據庫表是這樣的創建,

CREATE TABLE `nmlsstatelicenses` (`peopleid` int(11) DEFAULT NULL, `statelicensetypeid` int(11) DEFAULT NULL, `licensenumber` varchar(25) DEFAULT NULL) 

回答

1

您需要創建第三個實體,這將是一個鏈接的實體(如在數據庫中的許多一對多關係的鏈接表。這裏有一個例子:many-to-many relationships with additional information.

所以,你會在你的模型下面的實體:

public Employee 
{ 
    public string EmployeeId { get;set; } 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    public virtual ICollection<LicenseRegistration> RegisteredLicenses { get; set; } 
} 
public LicenseType 
{ 
    public int StateLicenseTypeId { get; set; } 
    public string State { get; set; } 
    public string LicenseName { get; set; } 
    public virtual ICollection<LicenseRegistration> RegisteredLicenses { get; set; } 
} 
public LicenseRegistration 
{ 
    //properties for the additional information go here 
    ///////////////////////////////////////////////////// 

    public int EmployeeId {get;set;} 
    [ForeignKey("EmployeeId")] 
    public Employee Employee {get;set;} 

    public int LicenseTypeId {get;set;} 
    [ForeignKey("LicenseTypeId")] 
    public LicenseType {get;set;} 
} 

然後,在你的DbContext文件,則需要DEFI Employee與LicenseRegistration之間以及LicenseType與LicenseRegistration之間的一對多關係。

希望這會有所幫助!

UPDATE 這裏是你將如何建立關係:

modelbuilder.Entity<LicenseRegistration>() 
      .HasRequired(lr => lr.LicenseType) 
      .WithMany(lt => lt.RegisteredLicenses) 
      .HasForeignKey(lr => lr.LicenseTypeId); 

modelbuilder.Entity<LicenseRegistration>() 
      .HasRequired(lr => lr.Employee) 
      .WithMany(e => e.RegisteredLicenses) 
      .HasForeignKey(lr => lr.EmployeeId); 
+0

這看起來像它會爲我工作。我已經考慮過這個問題,但是如果這三個類別應該關聯起來的話,它是不可能的。謝謝。 – Echofiend 2015-03-31 19:04:07

+0

我添加了代碼來配置dbcontext類中的關係。 – renakre 2015-03-31 19:10:51