使用基类查询和Entity Framework TPH模式将更改保存到子类属性 [英] Save changes to child class properties using base class query with Entity Framework TPH patten
问题描述
我有一个简单的TPH层次结构:
I have a simple TPH hierarchy:
public abstract class UserAccount
{
public string FirstName { get;set; }
}
public class InterpreterAccount : UserAccount
{
public string PhoneNumber { get;set; }
}
并在DbContext中:
and in DbContext:
//.......
public DbSet<UserAccount> UserAccounts { get; set; }
public DbSet<InterpreterAccount> InterpreterAccounts { get; set; }
此代码有效(将FirstName和PhoneNumber都保存到DB):
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();
这不会保存PhoneNumber属性
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.
所以问题是:我如何保存对通过查询基础对象集合检索的TPH层次结构的派生对象的更改在EF7中?
So the question is: how can I save changes to derived objects of TPH hierarchy retrieved by querying the base object collection in EF7?
推荐答案
...,并在接下来的10分钟内找到了解决方案。
...and found a solution in next 10 minutes. Still looks kinda ugly though.
要保存对通过基础对象集检索的派生对象的更改,我必须1)在查询时分离对象,2)根据以下内容附加到集合
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.
这篇关于使用基类查询和Entity Framework TPH模式将更改保存到子类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!