本文介绍了如何检查Linq-to-SQL对象是否已附加到DataContext?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象,该对象可能是通过普通的旧DataContext进行了充气,​​或者可能只是通过设置了它的.ID属性而被新建了.没有办法确定.我正在寻找从数据库中重新补水整个对象的方法.如果该对象是新创建的,则可以在表对象上调用.Attach(),并且可以毫无问题地从数据上下文刷新.但是,如果该对象已经从DataContext扩展,则会收到错误消息:无法附加已经存在的实体.".没有时间戳字段或类似的字段,仅使用一个整数主键来控制补液.我想知道是否有条件附加条件.这是代码-它可以按照我想要的方式工作,但这似乎是一种骇人听闻的解决方法:

I have an object that may have been inflated via a plain old DataContext, or may just have been new-ed up with just its .ID property set. There's no way to know for sure. I'm looking to rehydrate the entire object from whatever is in the database. If the object was new-ed up, I can call .Attach() on the table object and refresh from the Data Context with no trouble. But, if the object was already inflated from the DataContext I get the error: "Cannot attach an entity that already exists.". There's no timestamp field or anything like that - just an integer primary key being used to control the rehydration. I'd like to know if there's a way to conditionally attach. Here's the code - it works the way I want it to, but this seems a hackish way to go about it:

' myDC is a shared instance of a vanilla DataContext...
' myObj is an instance of a linqed-up `SomeLinqObject`
Dim tbl = myDC.GetTable(Of SomeLinqObject)()
Try
    tbl.Attach(myObj) ' <-- Wish I could just TryAttach() here!
Catch ex As Exception
    If ex.Message = "Cannot attach an entity that already exists." Then
        ' Do nothing
    Else
        Throw
    End If
End Try
myDC.Refresh(RefreshMode.OverwriteCurrentValues, myObj) ' Rehydrate

-编辑-

由于以撒的回答,这是经过修改的代码:

Thanks to Isaac's answer, here's the revised code:

Dim tbl = myDC.GetTable(Of SomeLinqObject)()
Dim isAttached = (tbl.GetOriginalEntityState(myObj) IsNot Nothing)
If Not isAttached Then tbl.Attach(myObj)
myDC.Refresh(RefreshMode.OverwriteCurrentValues, myObj) ' Rehydrate

推荐答案

表上的GetOriginalEntityState(T实体)-可能是您想要的.如果将从上下文中加载的实体传递给它,则它将返回上下文中包含的实体的原始版本.如果您将其传递给一个新实体(或者我相信一个根本不来自该上下文的实体),它将返回null.

GetOriginalEntityState(T entity) on Table -might- be what you're looking for. If you pass it an entity that you've loaded from the context, it returns the original version of the entity held in the context. If you pass it a new entity (or I believe one simply not sourced from that context), it returns null.

var context = new DataClasses1DataContext();
var person = context.Person.First();
var isAttachedToContext = context.Person.GetOriginalEntityState(person) != null; // returns true
var isNewEntityAttachedToContext = context.Peoples.GetOriginalEntityState(new Person()) != null; // returns false

道歉-答案在C#中,但我希望您能理解!

Apologies - answer is in C# but I hope you get the gist!

这篇关于如何检查Linq-to-SQL对象是否已附加到DataContext?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 22:34