Save changes to child class properties using base class query with Entity Framework TPH patten

血红的双手。 提交于 2019-12-12 06:32:35

问题


I have a simple TPH hierarchy:

public abstract class UserAccount
{
    public string FirstName { get;set; }
}

public class InterpreterAccount : UserAccount
{
    public string PhoneNumber { get;set; }
}

and in DbContext:

//.......
public DbSet<UserAccount> UserAccounts { get; set; }
public DbSet<InterpreterAccount> InterpreterAccounts { get; set; }

This code works (saves both FirstName and PhoneNumber to DB):

var account = _context.InterpreterAccounts.Single(i => i.Id == id);
account.FirstName = "Ivan";
account.PhoneNumber = "+123";
_context.SaveChanges();

And this doesn't save PhoneNumber property

var account = (InterpreterAccount)_context.UserAccounts.Single(i => i.Id == id);
account.FirstName = "Ivan";
account.PhoneNumber = "+123";
_context.SaveChanges();

But in real scenarios, the type of object is known only after it is retrieved, hence the need to query the base collection.

So the question is: how can I save changes to derived objects of TPH hierarchy retrieved by querying the base object collection in EF7?


回答1:


...and found a solution in next 10 minutes. Still looks kinda ugly though.

To save changes to derived object retrieved via base object set, I had to 1) detach object on querying and 2) attach to collection based on it's type

var account = _context.UserAccounts.AsNoTracking().Single(i => i.Id == id);
account.FirstName = "Ivan";
if (account is InterpreterAccount)
{
    _context.InterpreterAccounts.Attach(account);
    ((InterpreterAccount)account).PhoneNumber = "+123";
}
_context.SaveChanges();

Works but involves conditional logic which seems overkill. I'd like to see it working without it.



来源:https://stackoverflow.com/questions/36402298/save-changes-to-child-class-properties-using-base-class-query-with-entity-framew

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!