问题
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