情况如下。
有两种ElectricConsumer
即CommercialConsumers
& DomesticConsumers(Quaters)和一个Quater
被分配给一个Employee
。
下面是我的代码但遇到异常。
无法确定EFcodefirstDemo.CodeFistModel.Quater和类型之间关联的主要结尾 EFcodefirstDemo.CodeFistModel.Employee。这个的主要目的 必须使用以下任一方式显式配置关联 关系流畅的API或数据注释。
我知道我在某些地方犯了错误,因为我是EF的新手。希望你能解决这个问题。
public class Employee
{
public Employee()
{
MeterReadings = new List<MeterReading>();
MeterReadings = new List<MeterReading>();
}
[Key]
[Column(Order = 1)]
public int EmployeeID { get; set; }
[Key]
[Column(Order = 2)]
public Int64 EmployeeNo { get; set; }
public String EmployeeName { get; set; }
[DefaultValue(true)]
public bool Gender { get; set; }
[DefaultValue(true)]
public bool HasResidence { get; set; }
public bool IsInDivision { get; set; }
public int? ManagerID { get; set; }
public virtual Employee Manager { get; set; }
public virtual Department Deparment { get; set; }
public int QuaterID { get; set; }
[ForeignKey("QuaterID")]
public virtual Quater Quater { get; set; }
public virtual ICollection<MeterReading> MeterReadings { get; set; }
}
public partial class ElectricConsumer
{
[Key]
public int ElectricConsumerID { get; set; }
public String Area { get; set; }
[MaxLength(350)]
public String Address { get; set; }
public virtual ICollection< Meter> Meters { get; set; }
}
public partial class Quater : ElectricConsumer
{
public Quater()
{
// Meters = new List<Meter>();
}
public int QuaterNo { get; set; }
public int QuaterPortionNo { get; set; }
public virtual Employee Employee { get; set; }
}
public partial class CommericalCustomer : ElectricConsumer
{
public CommericalCustomer()
{
// Meters = new List<Meter>();
}
public String Name { get; set; }
[Index("NicIndex", IsUnique = true)]
public Int64 NIC { get; set; }
public int ShopNo { get; set; }
}
public partial class Meter
{
public Meter()
{
InstalledDate = DateTime.Now;
MeterReadings = new List<MeterReading>();
ElectricBills = new List<ElectricBill>();
}
[Key]
[Column(Order = 1)]
public int MeterID { get; set; }
[Key]
[Column(Order = 2)]
public int MeterNo { get; set; }
[DefaultValue(1)]
public int Phase { get; set; }
public DateTime InstalledDate { get; set; }
[DefaultValue(true)]
public bool IsOperating { get; set; }
public virtual ElectricConsumer ElectricConsumer { get; set; }
public virtual ICollection<MeterReading> MeterReadings { get; set; }
public virtual ICollection<ElectricBill> ElectricBills { get; set; }
}
答案 0 :(得分:15)
启动该异常是因为您尝试配置一对一关系,但未指定哪个结尾是关系中的主体。 Principal end是将首先插入的,并且可以在没有依赖的情况下存在的那个。 依赖结束是必须在主体之后插入的结尾,因为它具有主体的外键。要解决此特定问题,您可以使用Required
数据注释(我认为Quater
实体在这种情况下是依赖项):
public partial class Quater : ElectricConsumer
{
//...
[Required]
public virtual Employee Employee { get; set; }
}