我遇到了 Entity Framework 的问题,这是错误:无法确定“Force.Data.Models.Employee_Office”关系的主体端。多个添加的实体可能具有相同的主键。 我无法弄清楚问题出在哪里,我已经盯着它看了三个小时了。这是代码,有人能给我指出正确的方向吗,因为我似乎做不到:
Employee.cs
public partial class Employee : Person, IUser<int> {
public int Id { get; set; }
#region Relationship Properties
public byte CompanyId { get; set; }
public short OfficeId { get; set; }
public int? ManagerId { get; set; }
public virtual ICollection<Address> Addresses { get; private set; }
public virtual Company Company { get; set; }
public virtual ICollection<Device> Devices { get; private set; }
public virtual ICollection<Email> Emails { get; private set; }
public virtual ICollection<Employee> Employees { get; private set; }
public virtual Employee Manager { get; set; }
public virtual Office Office { get; set; }
public virtual ICollection<Phone> Phones { get; private set; }
public virtual ICollection<Role> Roles { get; private set; }
#endregion
}
Office.cs
public partial class Office {
public short Id { get; set; }
#region Relationship Properties
public int AddressId { get; set; }
public short RegionId { get; set; }
public virtual Address Address { get; set; }
public virtual ICollection<Employee> Employees { get; private set; }
public virtual ICollection<Job> Jobs { get; private set; }
public virtual ICollection<Lead> Leads { get; private set; }
public virtual ICollection<Phone> Phones { get; private set; }
public virtual Region Region { get; set; }
#endregion
}
EmployeeConfiguration.cs
internal sealed class EmployeeConfiguration : EntityTypeConfiguration<Employee> {
public EmployeeConfiguration() {
this.ToTable("Employees");
this.HasKey(
k =>
k.Id);
#region Properties
#endregion
#region Relationships
/// Employee has a 1:* relationship with Offices.
this.HasRequired(
t =>
t.Office).WithMany(
t =>
t.Employees).HasForeignKey(
k =>
k.OfficeId);
#endregion
}
}
OfficeConfiguration.cs
internal sealed class OfficeConfiguration : EntityTypeConfiguration<Office> {
public OfficeConfiguration() {
this.ToTable("Offices");
this.HasKey(
k =>
k.Id);
#region Properties
this.Property(
p =>
p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
#endregion
#region Relationships
#endregion
}
}
这也是生成的数据库的屏幕截图,我觉得还不错。我不认为是数据库在对我大喊大叫,而是 EF 对某些事情感到困惑......
请您参考如下方法:
所以,我是个白痴,问题一直都在看着我……结果是 Seed 方法失败了。我在其中添加了 40 个 Employee 对象,但其中一个对象没有分配 Office,这就是它失败的原因。呃,我需要小睡一下......
