基础类对几个派生类的快速收集-EF核心

问题描述 投票:1回答:1

我在将基类的子实体的集合强制转换为所有派生类时遇到麻烦。让我为您提供一个示例:

public class Household {
    public int Id {get; set;}
    public virtual ICollection<Person> Persons {get; set;}
}

public abstract class Person {
    public int Id {get; set;}
}

public class Parent : Person {
    public int Income {get; set;}
}

public class Child : Person {
    public string School {get; set;}
}

[当我想将孩子强制转换为特定的派生类时,当我尝试选择带有子集合Persons的Household类的实体时,就会出现此问题。

我尝试了以下查询,但未成功:

var household = Context.Households.Where(h => h.Id = id)
                .Include(hp => hp.Persons).OfType<Parent>().OfType<Child>()
                .FirstOrDefault();

(生成类子类不包含正确定义的错误。

var household = Context.Households.Where(h => h.Id = id)
                .Include(hp => hp.Persons).OfType<Parent>()
                .Include(hpp => hpp.Persons).OfType<Child>()
                .FirstOrDefault();

(生成类Parent不包含Person定义的错误]

我想在Household实体上有两个派生类的集合,而不仅仅是基类。

entity-framework ef-core-3.1
1个回答
0
投票

因此,我发现EF Core可以正常工作,是Controller在API调用期间丢失了子级的多态属性。为了解决这个问题,我使用以下两个来源作为准则:DotNet SerializationPolymorphic Deserialization

要获得我简单使用的派生类:

var household = Context.Households.Where(h => h.Id = id)
                .Include(hp => hp.Persons).FirstOrDefault();

我基于JsonConverter的实现,并得到以下代码:

编辑的类:

public class Household {
    public int Id {get; set;}
    public virtual ICollection<Person> Persons {get; set;}
}

public abstract class Person {
    public int Id {get; set;}
    public string Discriminator {get; private set;} 
    // The discriminator actually exists in the inherited parent table, 
    // I just want to attach it to my entities so I can identify to which subclass it belongs to
}

public class Parent : Person {
    public int Income {get; set;}
}

public class Child : Person {
    public string School {get; set;}
}

JsonConverter:

 public class PersonConverter: JsonConverter<Person>
    {
        public override bool CanConvert(Type typeToConvert) =>
            typeof(Person).IsAssignableFrom(typeToConvert);

        public override Person Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            if (reader.TokenType != JsonTokenType.StartObject)
            {
                throw new JsonException();
            }

            Person person;
            using (var jsonDocument = JsonDocument.ParseValue(ref reader))
            {
                // Using camelCase properties in my front-end application, therefore ToLower()
                if (!jsonDocument.RootElement.TryGetProperty(nameof(Person.Discriminator).ToLower(), out var typeProperty))
                {
                    throw new JsonException();
                }

                var type = typeProperty.GetString();
                var jsonObject = jsonDocument.RootElement.GetRawText();
                switch (type)
                {
                    case nameof(Parent):
                        person = (Parent)JsonSerializer.Deserialize(jsonObject, typeof(Parent));
                        break;
                    case nameof(Child):
                        person = (Child)JsonSerializer.Deserialize(jsonObject, typeof(Child));
                        break;
                    default:
                        throw new JsonException();
                }
            }
            return person;
        }
        public override void Write(Utf8JsonWriter writer, Person value, JsonSerializerOptions options)
        {

            if (value is Parent parent)
            {
                // Using camelCase properties in my front-end application
                JsonSerializer.Serialize(writer, parent, new JsonSerializerOptions
                {
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
                });
            } 
            else if (value is Child child)
            {
                // Using camelCase properties in my front-end application
                JsonSerializer.Serialize(writer, child, new JsonSerializerOptions
                {
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
                });
            }
            else
            {
                throw new NotSupportedException();
            }
        }
    }

然后我在启动过程中将其连接到控制器。

services.AddControllers().AddJsonOptions(options =>
{
    options.JsonSerializerOptions.Converters.Add(new PersonConverter());
});

推荐问答