简体   繁体   English

如何在 EFCore 中覆盖实体保存?

[英]How to override entity saving, in EFCore?

I want to store a List of objects in my model but I know EFCore doesn't support that.我想在我的模型中存储一个对象列表,但我知道 EFCore 不支持。 To work around it I have created a private string attribute on the model to hold the IDs of the objects in the list.为了解决这个问题,我在模型上创建了一个私有字符串属性来保存列表中对象的 ID。 My intention is to populate the list in the constructor of the class when it is restored.我的目的是在恢复时在类的构造函数中填充列表。 My class is as follows:我的课如下:

public class Visitor
{
    public int ID { get; set; }

    private string _DepartmentIds { get; set; }

    public List<Department> Departments { get; set; }

    public Visitor()
    {
        if (_DepartmentIds.Length > 0)
        {
            Departments = JsonConvert.DeserializeObject<List<Department>>(_DepartmentIds);
        }
        else
        {
            Departments = new List<Department>();
        }
    }
}

I have two problems.我有两个问题。 One is that _DepartmentIds does not get saved / tracked by EFCore.一是 _DepartmentIds 不会被 EFCore 保存/跟踪。 I presume because it is private.我想是因为它是私人的。 The second is I need to create a method that will read the IDs from the department list to put them into the _DepartmentIds string but I don't know how to call this method on the object's saving.第二个是我需要创建一个方法,该方法将从部门列表中读取 ID,将它们放入 _DepartmentIds 字符串中,但我不知道如何在保存对象时调用此方法。 Is it possible to override or extend the entity model saving in EFCore?是否可以覆盖或扩展保存在 EFCore 中的实体模型?

EDIT: I'm using deserialization rather than just concatenating IDs with a separator because I might want to expand this later.编辑:我正在使用反序列化,而不仅仅是将 ID 与分隔符连接,因为我可能想稍后扩展它。

For One:Many relationships, you should instead be creating a separate tables and joining them.对于 One:Many 关系,您应该创建一个单独的表并加入它们。 The schema should be something like:架构应该是这样的:

public class Visitor {
    public int ID { get; set; }
    public List<Department> Departments { get; set; }
}

public class Department {
    public int ID { get; set; }
    public int VisitorID { get; set; }

    [ForeignKey(nameof(VisitorID))]
    public Visitor Visitor { get; set; }
}

If you don't want to have the Visitor object in Department , you could also configure it through the fluent API using something like:如果您不想在Department拥有Visitor对象,您还可以使用以下内容通过 fluent API 配置它:

entity.HasOne<Visitor>()
    .WithMany()
    .HasForeignKey(department => department.VisitorID);

When you perform lookups on Visitor , you will then be able to use the Include function to include all the related Departments.当您在Visitor上执行查找时,您将能够使用Include功能来包括所有相关部门。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM