【问题标题】:ADO.net Entity Framework: Update only certian properties on a detached entityADO.net 实体框架:仅更新分离实体上的某些属性
【发布时间】:2009-07-22 20:59:35
【问题描述】:

我想在不先从数据库加载实体的情况下更新实体。

我已经完成了这一点,但只是通过了解所有实体属性然后使用“attachto”方法。

我的问题是我不希望我的应用程序需要记住所有属性。示例:

 Dim customerEntitiy As New shopper
 customerEntitiy.shopper_id = CustomerData.CustomerID
 customerEntitiy.market_code = CustomerData.MarketSector
 customerEntitiy.email = CustomerData.Email
 customerEntitiy.modified = DateTime.Now
 context.AttachTo("shopper", customerEntitiy)
 context.SaveChanges()

该实体上还有一个“已创建”字段。我不想通过我的 n 层应用程序一直传递这个“创建”日期。保存到数据库时如何“不更新”该字段?谢谢! 保罗

【问题讨论】:

  • 虽然可以做你想做的事,但不推荐这样做,因为实体可能没有直接链接到表。例如,我使用与视图关联的实体,并使用过程进行更新。这种方法会产生非常不利的影响...

标签: .net vb.net entity-framework ado.net


【解决方案1】:

我想通了,基本上你用一个存根代替,附加它,然后只设置你想要更新的道具。实体框架只会更新改变的东西。

Dim customerEntitiy As New commerce_shopper
customerEntitiy.shopper_id = CustomerData.CustomerID 'this is the primary key'
context.AttachTo("commerce_shopper", customerEntitiy)
customerEntitiy.market_code = CustomerData.MarketSector
customerEntitiy.email = CustomerData.Email
customerEntitiy.modified = DateTime.Now
context.SaveChanges()

这会绕过“创建”日期字段。

【讨论】:

  • 您能否告诉我们您在这种情况下所说的“存根”是什么意思。我们也遇到了同样的问题,想知道您是如何解决的。
  • 基本上您正在创建一个新的数据库对象,然后为其分配主键(.shopper_id = PK),然后使用 AttachTo 将其放在上下文中。改变你的东西,然后点击保存。
【解决方案2】:

我认为如果不先从数据库加载实体,就不可能使用保存更改来更新实体。您拥有的代码将生成插入语句,而不是更新。

您可能能够使用存储过程来完成您尝试做的事情,它只更新指定的文件。

【讨论】:

  • 我可以通过 Linq to Sql 来代替吗?
  • 我没有用过Linq to SQL,但我想你会遇到同样的问题。
【解决方案3】:
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多