Foundry Entity Framework Entities in the “Wrong” Direction

I use the Entity Framework and have an inheritance structure with a basic Entity (let’s call it Customer) and a derived Entity, let it call AccountCustomer. The difference is that AccountCustomer has additional information (for example, payment terms, etc.) stored in a separate table in the database and, therefore, additional properties in Entity.

I want to allow users to "promote" a particular Client as an AccountCustomer. I need to keep the same primary key (a composite key that is visible to users and used as a client reference).

Currently, I feel that calling a stored procedure to create an additional entry in the Accounts table is the only way, but so far we have not bypassed the Entity Framework, so we would prefer to avoid this technique if possible.

Are there any solutions for Entity Framework?

0
source share
2 answers

This is one of the “Please Don't Do This” scenarios.

You think about it strictly in terms of tables, not in object-oriented terms.

A private customer is a specific customer. He never changes. Now his status can change, or he can acquire additional AccountProperties, but he never moves from being one of the types (Client) to another type (AccountCustomer). It just doesn’t make sense conceptually (the common fruit does not turn into an apple, does it? It starts like an apple with one status and ends like an apple with a new status), and this is certainly not possible in object-oriented .NET programming ... which would make impossible in ORM, like EF.

Therefore, please consider a reasonable way to conceptualize this, which will lead to a reasonable way to express it in object-oriented terms, which will lead to a reasonable solution to EF.

+4
source

I solved this by workaround.

  • Download all the base class navigation properties associated with it, including

var customer = db.Customers.Include("whatever dependince you have").FirstOrDefault(u=>u.UserId == userId); // you can repeat this for all your included

  • Cache of navigation properties for local variables, i.e. var profile = customer.Profile;
  • Delete the base class db.Customer.Remove(customer);
  • Create a class derrived var accountCustomer = new AccountCustomer();
  • Set all your properties and navigation properties from the base class, i.e.

accountCustomer.UserId = customer.UserId;

accountCustomer.Profile = profile; // do the same for all of the properties and navigation properties from the base class

  • Add new class back to db

this.Entry<T>(accountCustomer).State = EntityState.Added;

  • db.SaveChanges() call

What is it!

0
source

Source: https://habr.com/ru/post/920410/


All Articles