Wednesday 24 October 2007

LINQ and the DataContext Attach() method

I just found out today that it is possible (rather than passing a DataContext object around by reference or refetching the objects), to "re-attach" objects to another data context. You can then perform updates on the object and related collection. See this article for more details:
http://blogs.msdn.com/dinesh.kulkarni/archive/2007/10/08/attach-if-you-have-something-detached.aspx

1 comment:

Oscar said...

Hello. I am hoping you can help. I am developing a tiered website using Linq to Sql. I created a new class(or object) in DBML designer called memberState. This object is not an actual table in the database. I have this method in my middle layer:



public override IEnumerable(memberState) GetMembersByState(string @state)

{

using (BulletinWizardDataContext context = DataContext)

{

IEnumerable(memberState) mems = (from m in context.Members

join ma in context.MemberAddresses

on m.UserId equals ma.UserId

join s in context.States

on ma.StateId equals s.StateId

where s.StateName == @state

select new memberState

{

userId = m.UserID,

firstName = m.FirstName,

middleInitial = m.MiddleInitial,

lastName = m.LastName,

createDate = m.CreateDate,

modifyDate = m.ModifyDate

}).ToArray(memberState)();

return mems;

}

}



The tables in my joins (Members, States, and MemberAddresses are actual tables in my Database). I created the object memberStates so I could use it in the query above (notice the Select New memberState. When the data is updated on the web page how do I persist the changes back to the Member Table? My Member Table consists of the following columns: UserId, FirstName, MiddleInitial, LastName, CreateDate, ModifyDate. I am not sure how save the changes back to the database.



Thanks,