Eri*_* J. 6 poco code-first entity-framework-4
我有一个相当深的对象层次结构,我试图坚持使用Entity Framework 4,POCO,PI(Persistence Ignorance)和Code First.突然之间,当我突然意识到不使用new()运算符时,事情开始变得很好.最初编写时,对象经常使用new()来创建子对象.
相反,我正在使用我对存储库模式的看法来根据需要创建所有子对象.例如,给定:
class Adam
{
List<Child> children;
void AddChildGivenInput(string input) { children.Add(new Child(...)); }
}
class Child
{
List<GrandChild> grandchildren;
void AddGrandChildGivenInput(string input) { grandchildren.Add(new GrandChild(...)); }
}
class GrandChild
{
}
Run Code Online (Sandbox Code Playgroud)
("GivenInput"表示此处未显示的某些处理)
我定义了一个AdamRepository像:
class AdamRepository
{
Adam Add()
{
return objectContext.Create<Adam>();
}
Child AddChildGivenInput(Adam adam, string input)
{
return adam.children.Add(new Child(...));
}
GrandChild AddGrandchildGivenInput(Child child, string input)
{
return child.grandchildren.Add(new GrandChild(...));
}
}
Run Code Online (Sandbox Code Playgroud)
现在,这很好用.但是,我不再"无知"我的持久性机制,因为我放弃了new()运算符.
此外,我有一个贫血领域模型的风险,因为这么多的逻辑最终存储在存储库而不是域对象中.
经过多次讨论,一个问题:
或者更确切地说......
有时试图去POCO/Persistence Ignorance路线感觉就像在上游游泳,有时候感觉就像游泳Niagra瀑布.不过,我还是想相信......
以下几点可能有助于回答您的问题:
\n\n在您的类中,您有一个用于子集合的字段和一个添加到子集合的方法。一般而言,EF(不仅仅是 Code First)当前要求集合作为属性呈现,因此当前不支持此模式。与班级互动的方式更加灵活是 EF 的常见要求,我们的团队目前正在研究如何支持这一点
\n\n您提到您需要在上下文中显式注册实体,但 \xe2\x80\x99 不一定是这种情况。在以下示例中,如果 GetAdam() 返回附加到底层上下文的 Adam 对象,则当您保存并插入数据库时,EF 将自动发现新的子 Cain。
\n\nvar adam = myAdamRepository.GetAdam();
\n\nvar cain = new Child();
\n\n亚当.Children.Add(该隐);
\n\n〜罗文
\n| 归档时间: |
|
| 查看次数: |
1854 次 |
| 最近记录: |