2013-08-06 100 views
2

我有一个遗留表,我需要将我的应用程序连接到。我使用的是代码优先的POCO模型。我有以下类:代码与实体框架的第一个关系,流利的API

public class Equipment 
{ 
    [Key] 
    public string EquipmentId { get; set; } 
    public string OriginatorId { get; set; } 

    public virtual Employee Employee { get; set; } 
} 

public class Employee 
{ 
    [Key] 
    [Column("employee_id")] 
    public string EmployeeId { get; set; } 

    public string EmployeeName { get; set; } 

    [ForeignKey("OriginatorEmployeeId")] 
    public virtual Equipment Equipment { get; set; } 
} 

我需要在Employee类映射到雇员在设备类OriginatorEmployeeId。

此外,遗留表由Employee类表示。该表实际上被命名为employee(小写),EmployeeId列被命名为“employee_id”。我想保持我的类和属性的名称与应用程序的其余部分一致,因此Employee和EmployeeId一致。

下面是我用流利的API尝试:

modelBuilder.Entity<Employee>().Map(m => 
    { 
     m.MapInheritedProperties(); 
     m.ToTable("employee"); 
    }); 

    modelBuilder.Entity<Equipment>() 
       .HasOptional<Employee>(u => u.Employee) 
       .WithOptionalDependent(c => c.Equipment).Map(p => p.MapKey("OriginatorEmployeeId")); 

我可能混合的东西我不需要。我现在得到的错误是:

Multiplicity is not valid in Role 'Equipment_Employee_Source' in relationship 'Equipment_Employee'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'. 

任何帮助表示赞赏。

+0

您OnModelCreating事件我不熟悉实体框架,但应该将外键映射到像EquipmentId这样的真实ID而不是对象设备? – PmanAce

+0

谢谢PmanAce。通过实体框架(EF),Employee类中的Equipment对象是导航属性。这是EF代表关系的方式 – steveareeno

+0

你试图达到什么样的关系? – Pluc

回答

4

员工记录是否可以与多个设备记录关联?如果他们可以,那么您的员工POCO应该包含代表员工和设备之间一对多关系的集合属性。

public virtual ICollection<Equipment> Equipments {get;set;} 

你的配置应该再作相应的调整,以显示这种关系:

modelBuilder.Entity<Employee>() 
      .HasMany<Equipment>(u => u.Equipments) 
      .WithRequired(c => c.Employee).HasForeignKey(p => p.OriginatorId); 

它也像你需要设置你的列名映射配置为好。因此,我建议你为每一个资料波苏斯的一个单独的配置文件,使其更易于管理的配置,则只需添加这些配置到modelbuilder.Configurations集合在你的DbContext

public class EmployeeConfiguration : EntityTypeConfiguration<Employee> 

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{ 
     modelbuilder.Configurations.Add(new EmployeeConfiguration()); 
} 
+0

就是这样!我必须将导航属性更改为集合,并在发布时更改流畅的API配置。谢谢! – steveareeno

相关问题