我遇到了Entity Framework的问题,这就是错误:Unable to determine the principal end of the 'Force.Data.Models.Employee_Office' relationship. Multiple added entities may have the same primary key.
我无法弄清问题是什么,我一直在盯着它现在三个小时。这是代码,有人可以指出我正确的方向,因为我似乎无法:
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对某些事情感到困惑......
答案 0 :(得分:4)
所以,我是个白痴,这个问题一直在看着我......事实证明,Seed
方法失败了。在其中我添加了40个Employee
个对象,但其中一个没有分配Office
,这就是它失败的原因。呃,我需要小睡......