【问题标题】:Code first relationships with entity framework, fluent API与实体框架的代码优先关系,流畅的 API
【发布时间】:2013-08-06 14:57:44
【问题描述】:

我有一个需要将我的应用连接到的旧表。我正在使用代码优先的 POCO 模型。我有以下课程:

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 类中的 EmployeeId 映射到 Equipment 类中的 OriginatorEmployeeId。

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

这是我使用 fluent 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 '*'.

感谢任何帮助。

【问题讨论】:

  • 我不熟悉实体框架,但您的外键是否应该映射到像 EquipmentId 这样的真实 id 而不是对象 Equipment?
  • 感谢 PmanAce。使用实体框架 (EF),Employee 类中的 Equipment 对象是一个导航属性。这是 EF 表示关系的方式
  • 你想要达到什么样的关系?
  • 在 1:1 关系中,依赖实体的主键也是 Principal 的外键。
  • 这是一对多的。一名员工对多台设备。

标签: asp.net-mvc entity-framework fluent


【解决方案1】:

员工记录可以与多个设备记录相关联吗?如果可以,那么您的 Employee POCO 应该包含一个集合属性,表示 Employee 和 Equipment 之间的一对多关系。

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

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

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

您似乎还需要为列名映射设置配置。因此,我建议您为每个 POCO 创建一个单独的配置文件,以便更轻松地管理配置,然后只需将这些配置添加到 DBContext 的 OnModelCreating 事件中的 modelbuilder.Configurations 集合中

public class EmployeeConfiguration : EntityTypeConfiguration<Employee>

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

【讨论】:

  • 就是这样!我必须将导航属性更改为集合,并在您发布时更改流畅的 API 配置。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-31
  • 1970-01-01
  • 2012-10-11
  • 2017-07-05
  • 2011-08-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多