Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

244
Views
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

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!