我正在开发一个应用程序,在服务器上使用 asp.net core 2.2 和 ef core 2.2,在客户端使用 Angular 7。我无法弄清楚:
我有以下(简化的)模型:
public abstract class LegalEntity
{
public int Id { get; set; }
public int Name { get; set; }
public Address FiscalAddress { get; set; }
}
public class Organisation : LegalEntity
{
public Organisation(){}
public Organisation(LegalEntityType legalEntityType, string name, Address fiscalAddress)
{
LegalEntityType = legalEntityType;
Name = name;
}
public LegalEntityType LegalEntityType { get; set; }
}
public class LegalEntityType
{
public int Id { get; set; }
public int Name { get; set; }
public LegalEntityType(){}
public LegalEntityType(string name)
{
Name = name;
}
}
public class Person : LegalEntity
{
public Gender Gender { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public override string Name => string.Format("{0} {1}", FirstName, LastName);
}
public class Gender
{
public int Id { get; set; }
public int Name { get; set; }
}
public class Customer
{
public int Id { get; set; }
public Customer(){}
public Customer(LegalEntity legalEntity)
{
LegalEntity = legalEntity;
}
public LegalEntity LegalEntity { get; set; }
}
当我通过 API 将客户实体返回给客户时,有时法人实体是一个组织,有时是一个人。在返回哪种类型(组织或个人)之后,我希望将属性 LegalEntityType(如果是组织)或属性 Gender(如果是个人)呈现到 JSON 代码中。这是我的第一个问题,以下使它们都为空:
.Include(o => o.Customer).ThenInclude(o => o.LegalEntity)
因为这不会加载仅存在于继承实体中的导航属性。这是 JSON 字符串的摘录,以防万一
人:
...
"customer": {
"legalEntity": {
"gender": null,
"firstName": "Denis",
"lastName": "Testmann",
"name": "Denis Testmann",
"id": 9
},
...
组织:
...
"customer": {
"legalEntity": {
"legalEntityType": null,
"name": "Companyname GmbH",
"id": 6
},
...
应该出现的是以下内容:
人:
...
"customer": {
"Person": {
"gender": null,
"firstName": "Denis",
"lastName": "Testmann",
"name": "Denis Testmann",
"id": 9
},
...
组织:
...
"customer": {
"Organisation": {
"legalEntityType": null,
"name": "Companyname GmbH",
"id": 6
},
...
明确一点:客户可能是个人或组织,实体(组织和个人)都从法人实体继承,因此客户财产“法人实体”有时是个人,有时是组织。当我呈现 JSON 时,必须维护特定类型。
希望我足够清楚 - 请原谅我这么久,我想确保问题得到理解。