简体   繁体   English

名称不匹配时的实体框架代码优先映射

[英]Entity Framework Code First Mapping when Name Does Not Match

Suppose I have two entities that look like this: 假设我有两个看起来像这样的实体:

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;}
}

How can I setup a relationships such that Widgets.Include(x=>x.CreatedByEmployee) will get the employee data for the EmployeeId that is stored in Widget.CreatedBy ? 如何设置关系,使Widgets.Include(x=>x.CreatedByEmployee)将获取存储在Widget.CreatedByEmployeeId的员工数据?

I am fine with either a Migrations or Annotations solution. 我可以使用“迁移”或“注释”解决方案。

A common way to config an one to one relationship using Data Annotations is this: 使用数据注释配置一对一关系的一种常见方法是:

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;}
}

Also, consider add virtual keyword to your navigation properties if you want to use Lazy Loading. 另外,如果要使用延迟加载,请考虑将virtual关键字添加到导航属性。 In this msdn page you will find all the requirements. 在此msdn页中,您将找到所有要求。

In your case you're are configuring an unidirectional relationship, if you prefer to use Fluent Api, for example, overriding OnModelCreating method of you context, your configuration would be: 在您的情况下,您正在配置单向关系,如果您更喜欢使用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);
    }

In this case you don't need to specify that CreatedBy is also FK due to an EF requirement that the primary key of the dependent is also used as the foreign key. 在这种情况下,由于EF要求将依赖项的主键也用作外键, CreatedBy无需指定CreatedBy也是FK。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM