加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 我为什么要在LINQ To SQL存储库保存方法中使用Ge

发布时间:2020-12-16 06:57:40 所属栏目:asp.Net 来源:网络整理
导读:我正在看Steven Sanderson的书Pro ASP.NET MVC 2 Framework中的一个产品库中的保存方法示例: public void SaveProduct(Product product){ // if new product,attach to DataContext: if (product.ProductID == 0) productsTable.InsertOnSubmit(product); e
我正在看Steven Sanderson的书Pro ASP.NET MVC 2 Framework中的一个产品库中的保存方法示例:

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中的逻辑如果行:

else if (productsTable.GetOriginalEntityState(product) == null)

据我了解,GetOriginalEntityState()返回指定实体的原始状态..在这种情况下,该实体是产品.

所以这个if语句对我来说就是:“如果原来不存在那么……”但这没有意义,因为这本书说这检查我们正在修改已经存在的记录.

在这种情况下我应该如何理解GetOriginalEntityState?

编辑

顺便说一句,这段摘录来自第191页的第6章……以防万一有人拿到这本书并且想要查阅它.这本书在代码示例中只具有该功能,但它从未解释该函数的功能.

解决方法

这是一个小小的猜测,因为我从来没有真正使用过GetOriginalEntityState,但问题最让我感兴趣的是弄清楚发生了什么.

我认为这里的目的是检查产品是否仍附加到原始DataContext

这条线:

if (productsTable.GetOriginalEntityState(product) == null)

我认为如果产品已被解除或手动创建并且未由DataContext处理,则返回null.

从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调用返回vs仅创建类似Product p = new Product(){…};的实例.如果未附加,它将附加到DataContext并保留由于RefreshMode.KeepCurrentValues参数而修改的任何值(保留更新值).

然后是productsTable.Context.SubmitChanges();总是会发生,因为即使它被释放,GetOriginalEntityState也会确保它被附加,因此提交将起作用.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读