【问题标题】:How to use/persist POCO object relationships in EF?如何在 EF 中使用/持久化 POCO 对象关系?
【发布时间】:2012-08-06 16:11:21
【问题描述】:

我有一些看起来像这样的 POCO 对象:

public class Foo
{
    public int Id { get; set; }
    public string FooProperty { get; set; }
    public int BarId { get; set; }
    public virtual Bar Bar { get; set; }
}
public class Bar
{
    public int Id { get; set; }
    public string BarProperty { get; set; }
    public int FooId { get; set; }
    public virtual Foo Foo { get; set; }
}

每个 Foo 对象都只有一个 Bar(反之亦然)。

现在我想创建一对新的 Foo/Bar 对象。所以我这样做(这是我怀疑我出错的地方):

var foo = new Foo() { FooProperty = "hello" };

dbContext.Foos.Add(foo);

var bar = new Bar() { BarProperty = "world" };

foo.Bar = bar;

dbContext.SaveChanges();

您可能会说,我希望因为我“添加”了foo,所以bar 也将被添加,因为它是同一个对象图的一部分,但不是:它没有被添加 - 并且在调用 SaveChanges 之后,Bar 对象的 FooId 也没有更新(尽管 Foo 对象的 Id更新)。

所以,我的猜测是这种行为是因为我正在处理 POCO 而不是 EF 代理对象,因此没有“管道”来完成这项工作。我可以从Foo 对象中获取Id 并手动将其存储在Bar 对象中(反之亦然),然后对SaveChanges 进行更多调用,但显然这不是正确的方法。

所以,大概我需要创建 EF 代理对象而不是裸 POCO 对象。最好的方法是什么?

【问题讨论】:

  • 没有“错误”,但是数据库表没有按我的意愿更新,POCO 对象也没有更新。
  • 您是否在 DbContext 对象中进行了配置以将 BarId 和虚拟 Bar 属性链接在一起?我怀疑您的数据库包含其他字段,例如 Foo_Id 以及您的 FooId 如果您还没有
  • 是的,我做了一些 HasRequired/WithRequired 的东西。

标签: entity-framework ef-code-first poco entity-framework-5


【解决方案1】:

如果实体满足创建代理对象的要求,您可以通过从上下文本身调用 create 函数来完成这项工作:

    var foo = dbContext.Foos.Create();
    dbContext.Foos.Add(foo);
    var bar = dbContext.Bars.Create();
    foo.Bar = bar;
    dbContext.SaveChanges();

【讨论】:

  • 谢谢。我想它一定是这样的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-10
  • 2023-03-20
  • 2011-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-24
相关资源
最近更新 更多