简体   繁体   中英

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 ?

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. In this msdn page you will find all the requirements.

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:

    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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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