【发布时间】: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