我正在查看 Steven Sanderson 的书 Pro ASP.NET MVC 2 Framework 中 Products 存储库中保存方法的示例:
public void SaveProduct(Product product)
{
// if new product, attach to DataContext:
if (product.ProductID == 0)
productsTable.InsertOnSubmit(product);
else if (productsTable.GetOriginalEntityState(product) == null)
{
// we're updating existing product
productsTable.Attach(product);
productsTable.Context.Refresh(RefreshMode.KeepCurrentValues, product);
}
productsTable.Context.SubmitChanges();
}
我不明白
else if
中的逻辑线:else if (productsTable.GetOriginalEntityState(product) == null)
据我了解,
GetOriginalEntityState()
返回指定实体的原始状态。在这种情况下,实体是 product
.所以这个 else if 语句对我来说就像:“如果原件不存在那么......”但这没有意义,因为这本书说这会检查我们正在修改一个已经存在的记录。
我该怎么理解
GetOriginalEntityState
在这种情况下?编辑
顺便说一下,这段摘录来自第 6 章第 191 页……以防万一有人有这本书并想查一下。该书仅在代码示例中包含该函数,但从未解释该函数的作用。
最佳答案
这有点猜测,因为我从未真正使用过 GetOriginalEntityState
但这个问题激起了我想弄清楚发生了什么的兴趣。
我认为这里的目的是检查 product
依然附在原版DataContext
线路:
if (productsTable.GetOriginalEntityState(product) == null)
如果
product
,我认为这将返回 null已被分离或手动创建且未由 DataContext
处理.来自 MSDN :
This method returns the original state of an entity since it was either created or attached to the current DataContext. The original state of an entity that has been serialized and deserialized must be provided by an independent tracking mechanism and supplied when the entity is attached to a new DataContext. For more information, see Data Retrieval and CUD Operations in N-Tier Applications (LINQ to SQL).
我认为要理解的关键是:
This method returns the original state of an entity since it was either created or attached to the current DataContext.
GetOriginalEntityState
被使用,以便该方法可以接收一个对象,并选择尚未附加到 DataContext
的选项。 .附加含义,由 Linq To SQL 调用返回,而只是创建一个类似 Product p = new Product() { ... };
的实例.如果没有附加,它会附加到 DataContext
并保留由于 RefreshMode.KeepCurrentValues
而修改的任何值(保留更新值)参数。然后是
productsTable.Context.SubmitChanges();
总是发生,因为即使它被分离,GetOriginalEntityState
将确保它被附加,以便提交工作。
关于asp.net-mvc - 为什么我应该在我的 LINQ To SQL 存储库保存方法中使用 GetOriginalEntityState()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3472408/