1

假设我有看起来像这样的两个实体:实体框架代码优先映射时,名称不匹配

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)将获得的EmployeeId即雇员数据存储在Widget.CreatedBy

我很喜欢迁移或注解解决方案。

回答

2

到配置的一个使用数据注释一个关系的一种常用方法是这样的:

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页面中,您可以找到所有要求。

在你的情况你正在配置单向关系,如果你喜欢用流利的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); 
    } 

在这种情况下,你不需要指定CreatedBy也是FK,这是由于EF要求 从属关系的主键也用作外键。

+0

完美!非常感谢你! – Vaccano

+0

不用客气;) – octavioccl

+0

我更新了我的示例以更好地展示我的真实场景。 'Widget'有它自己的'WidgetId'。 – Vaccano