【发布时间】:2011-09-25 20:31:24
【问题描述】:
我正在从 EDMX 映射迁移到 EF 4.1 DbContext 和 Fluent 映射,并且我想使用 fluent API 映射字符串外键和外来对象。我有一个可选办公室的员工。我想要 Employee 类中的 OfficeId 和 Office 对象(这都是只读的,我不需要能够保存这些对象)。具有 int 键的对象工作正常,但我尝试了几个使用字符串键并获得相同的结果 - OfficeId 字段填充,但 Office 对象返回为空。在 SQL 分析器中检查正在查询数据,但未填充 office 对象。
public partial class Employee
{
public int Id { get; set; }
// snip irrelevant properties
public Office Office { get; set; } // this is (incorrectly) always null
public string OfficeId { get; set; }
public WorkGroup WorkGroup { get; set; } // this one with the int key is fine
public int? WorkGroupId { get; set; }
// snip more properties
}
public partial class Office
{
public string Id { get; set; }
public string Description { get; set; }
}
public partial class WorkGroup
{
public int Id { get; set; }
public string Code { get; set; }
}
根据下面 Ladislav 的反馈,我在 OnModelCreating 中这样映射它
modelBuilder.Entity<Employee>().HasKey(d => d.Id).ToTable("Employee", "ExpertQuery");
modelBuilder.Entity<Office>().HasKey(d => d.Id).ToTable("Office", "ExpertQuery");
modelBuilder.Entity<WorkGroup>().HasKey(d => d.Id).ToTable("WorkGroup", "ExpertQuery");
modelBuilder.Entity<Employee>()
.HasOptional(a => a.Office)
.WithMany()
.Map(x => x.MapKey("OfficeId")); // this one does not work
modelBuilder.Entity<Employee>()
.HasOptional(e => e.WorkGroup)
.WithMany()
.HasForeignKey(e => e.WorkGroupId); // this one works fine
我认为我缺少的字符串键有些微妙之处?我查询如下:
var employees = expertEntities.Employees.Include("Office").Include("WorkGroup").Take(10).ToList();
如果我省略 Employee 中的 OfficeId 字段,并像这样设置映射:
modelBuilder.Entity<Employee>()
.HasOptional(e => e.BusinessEntity)
.WithMany()
.Map(x => x.MapKey("OfficeId"));
然后填充office对象,但我需要Employee对象中的OfficeId字段。
【问题讨论】:
标签: entity-framework-4.1 foreign-key-relationship fluent