[英]Entity Framework Code First Mapping when Name Does Not Match
假设我有两个看起来像这样的实体:
public class Widget
{
public int WidgetId {get; set;}
public int CreatedBy {get; set;}
public Employee CreatedByEmployee {get; set;}
}
public class Employee
{
public int EmployeeId {get; set;}
public String EmployeeName {get; set;}
}
如何设置关系,使Widgets.Include(x=>x.CreatedByEmployee)
将获取存储在Widget.CreatedBy
的EmployeeId
的员工数据?
我可以使用“迁移”或“注释”解决方案。
使用数据注释配置一对一关系的一种常见方法是:
public class Widget
{
[Key,ForeignKey("CreatedByEmployee")]
public int CreatedBy {get; set;}
public virtual Employee CreatedByEmployee {get; set;}
}
public class Employee
{
[Key]
public int EmployeeId {get; set;}
public String EmployeeName {get; set;}
}
另外,如果要使用延迟加载,请考虑将virtual
关键字添加到导航属性。 在此msdn页中,您将找到所有要求。
在您的情况下,您正在配置单向关系,如果您更喜欢使用Fluent Api,例如,覆盖上下文的OnModelCreating
方法,则您的配置应为:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Widget>().HasKey(w=>w.CreatedBy);
modelBuilder.Entity<Widget>().HasRequired(e => e.CreatedByEmployee ).WithOptional();
base.OnModelCreating(modelBuilder);
}
在这种情况下,由于EF要求将依赖项的主键也用作外键, CreatedBy
无需指定CreatedBy
也是FK。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.