简体   繁体   中英

Proxy Items in Entity Framwork Core

Is it possible to create as a proxy element in EF Core?

For example, in the database there is the element with the id 1, which has the name Example . The second element with id 2 has no name (is null), but has a reference to element 1 ("id_replace"). In this case I would like the name returned by item 2 to be "Example" like item 1. And also the "Includes" quote to item 1 references.

The reason I have such a strange idea is that I need to have linked the elements, and if element 1 changes, the changes made are displayed on element 2 as well.

Example Registers in Database

Sure you can. Assuming that your class is:

public class YourClass
{
    public int id { get; set; }
    public string name { get; set; }
    public int? id_replace { get; set; }
}

In your class, you need to have the one to many referencing properties:

    public YourClass parent { get; set; }
    public IList<YourClass> children { get; set; }

Then, in your DbContext class, in the override OnModelCreating function, you need to have a relationship set in the fluent API that indicates that id_replace is a self-referencing foreign key:

modelBuilder.Entity<YourClass>(entity =>
{
     entity.HasOne(x => x.parent)
         .WithMany(x => x.children)
         .HasForeignKey(x => x.id_replace)
         .OnDelete(DeleteBehavior.SetNull);
});

After doing that(and migrating), you have the necessary navigation properties to be able to add computed properties that do not represent anything in the database. So your class can have the property:

    public int alt_name => name??$"\"{parent.name}\"";

So eventually, your class will look something like this:

public class YourClass
{
    public int id { get; set; }
    public string name { get; set; }
    public int? id_replace { get; set; }
    public YourClass parent { get; set; }
    public IList<YourClass> children { get; set; }
    public int alt_name => name??$"\"{parent.name}\"";
}

That way, you can discard the name property and just call on the alt_name property. You can even set the name property as private or change the names to avoid confusion.

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