更新实体框架中的对象的列表属性4.3 - 代码第一,N层 [英] Updating an Object's List Property in Entity Framework 4.3 - Code First, N-Tier

查看:91
本文介绍了更新实体框架中的对象的列表属性4.3 - 代码第一,N层的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在n层情景中,数据层应如何更新EF 4.3中对象的List属性?

In an n-tier scenario, how is the data layer supposed to update List properties of an object in EF 4.3?

假设我们有这个类:

public class Foo
{
  public int Id { get; set; }
  public string Name { get; set; }
  public List<Bar> Bars { get; set; }
}

在保存/更新Id和Name方面效果很好,但是Bars属性被忽略。

This works well as far as saving/updating Id and Name, but the Bars property is ignored.

protected void SaveChanges(Foo foo)
{
  this.Database.Entry<Foo>(foo).State = GetState(foo);
  this.Database.SaveChanges();
}

由于原始上下文(检索到Foo)不再在内存中,数据层应该如何处理保存Bars属性的更新? EF如何知道哪些条款已被删除,哪些已被更新,哪些被添加?

Since the original context (that retrieved Foo) is no longer in memory, how should the data layer deal with saving updates to the Bars property? How does EF know which Bar items have been removed, which have been updated, and which have been added?

注意:我可以循环遍历每个条目,并将其与原来,但我猜,EF不应该这样工作。这样看起来很乏味和不正确。

Note: I could loop through each Bar item and compare it to the original, but I'm guessing EF isn't supposed to work that way. That seems tedious and incorrect.

推荐答案


EF如何知道哪些条目已被删除,哪些已经
已更新,哪些已被添加?

How does EF know which Bar items have been removed, which have been updated, and which have been added?

如果您将自己写持久性如何知道更改?我想你会选择以下两个选项之一:

If you would write persistence yourselves how should it know about changes? I suppose you would choose one of two options:


  • 您将查询数据库的当前状态,并将其与接收状态进行比较,以查找已更改的内容

  • 您将在课程中添加一些帮助字段,并让客户告诉您有什么变化

在这两种情况下,您将使用有关更改的信息来生成正确的SQL。

In both cases you would use information about changes to generate correct SQL.

EF仅解决最后一点(SQL生成),但您仍然有责任告诉它发生了什么变化。

EF solves only the last point (SQL generation) but you are still responsible for telling it what has changed.

这篇关于更新实体框架中的对象的列表属性4.3 - 代码第一,N层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆