添加额外的列连接表
问题描述:
我目前有雇员模型添加额外的列连接表
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)
答
您需要创建第三个实体,这将是一个链接的实体(如在数据库中的许多一对多关系的链接表。这里有一个例子: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);
这看起来像它会为我工作。我已经考虑过这个问题,但是如果这三个类别应该关联起来的话,它是不可能的。谢谢。 – Echofiend 2015-03-31 19:04:07
我添加了代码来配置dbcontext类中的关系。 – renakre 2015-03-31 19:10:51