[英]Entity Framework 6.1: Multiple added entities may have the same primary key
我遇到了实体框架问题,这是错误: Unable to determine the principal end of the 'Force.Data.Models.Employee_Office' relationship. Multiple added entities may have the same primary key.
Unable to determine the principal end of the 'Force.Data.Models.Employee_Office' relationship. Multiple added entities may have the same primary key.
我无法弄清楚问题是什么,我已经盯着它看了三个小时。 这是代码,有人可以指出正确的方向,因为我似乎无法:
员工
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 beinc对某些事情感到困惑...
所以,我是个白痴,问题一直困扰着我……原来是Seed
方法失败了。 在其中添加了40个Employee
对象,但是其中一个没有分配给Office
,这就是失败的原因。 gh,我需要午睡...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.