【发布时间】:2019-06-08 18:35:04
【问题描述】:
我正在尝试使用 EF Core 设计数据模型。
我有一个 InformalOranization LegalOrganization 和 Person 继承自的 Party 类(超类)。只有 LegalOrganization 和 Person 有 TaxNumber。因此,这 2 个类具有 TaxNumber 类属性。
public abstract class Party
{
public Party()
{
Names = new List<Name>();
}
public int PartyId { get; set; }
public PartyType PartyType { get; set; }
public string Comment { get; set; }
}
public class Person : Party
{
public Person()
{
}
public Gender Gender { get; set; }
public DateTime Birthday { get; set; }
public TaxIdentificationNumber TaxIdentificationNumber { get; set; }
}
public class LegalOrganization : Organization
{
public LegalOrganization()
{
}
public DateTime RegistrationDate { get; set; }
public bool IsProfitable { get; set; }
public TaxIdentificationNumber TaxIdentificationNumber { get; set; }
}
public class TaxIdentificationNumber
{
public int TaxIdentificationNumberId { get; set; }
public string Number { get; set; }
public DateTime IssueDate { get; set; }
public int PartyId { get; set; }
public Party Party { get; set; }
}
我收到此错误。
未处理的异常:Microsoft.EntityFrameworkCore.DbUpdateException:更新条目时出错。有关详细信息,请参阅内部异常。 ---> System.Data.SqlClient.SqlException:MERGE 语句与 FOREIGN KEY 约束“FK_TaxIdentificationNumbers_Parties_PartyId”冲突。冲突发生在数据库“Teknowhow.DataModel080519_01”、表“dbo.Parties”、列“PartyId”中。 声明已终止。
【问题讨论】:
-
您可以添加另一个派生自
Party并包含成员TaxIdentificationNumber的类。Person和LegalOrganization然后派生自这个附加类。 -
好吧,根据你的例子,它应该在抽象类中,因为它是一个公共属性
-
@noox 我只是编辑 LegalOrganization 类。它继承自组织。并非所有组织都应纳税。非正式组织(未经注册)不是。因此,LegalOrganization 源于组织。并且 InformalOrganization (that) 在这个问题上并不重要,也继承自 Organization,并且不征税。
-
我假设您在
Organization中也有字段。如果没有:你真的需要它吗?否则我不知道一个好的解决方案。您可以在Party中使用TaskIdentifiacationNumber,但也可以在InformalOrganizations中使用。或者两个派生类中的两个不同名称的 TaxIdentifactionNumber。 -
我刚刚偶然发现了支持字段 (docs.microsoft.com/en-us/ef/core/modeling/backing-field)。也许您可以在
Party中添加一个受保护字段_taxIdentIficationNumber,将其定义为支持字段,并仅在Person和LegalOrganization中公开具有公共属性的受保护字段。但我没有尝试过,它肯定不完美。
标签: c# .net sql-server entity-framework-core