简体   繁体   中英

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. To work around it I have created a private string attribute on the model to hold the IDs of the objects in the list. 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. 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. Is it possible to override or extend the entity model saving in EFCore?

EDIT: I'm using deserialization rather than just concatenating IDs with a separator because I might want to expand this later.

For One:Many relationships, you should instead be creating a separate tables and joining them. 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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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