How do I check whether a Linq-to-SQL object is already attached to a 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 lookin开发者_如何学JAVAg 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
-- EDIT --
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 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
Apologies - answer is in C# but I hope you get the gist!
精彩评论