Tuesday, 6 August 2013

Updating a record using Entity Framework context without manually setting properties

Updating a record using Entity Framework context without manually setting
properties

I am trying to update a record using Entity Framework but want to avoid
manually setting each property and then calling save changes. I have an
instance of this class bound to a dataform that updates all its properties
as a user changes them. The nicest way I can see using this would be to
set the object in the context equal to the object bound to my dataform but
this does not work. I tried removing the object from the context then
adding the dataform bound object but it creates a completely new record (I
expected this but decided it was worth a shot to try it out). I assume
there is some type of flag with in the context that is used to detect if a
record is a new row or not considering the fact that replacing the context
object with the databound object (which has the same pk value) does not
work.
using (var scope = new TransactionScope())
{
try
{
using (var context = new CIS_DEVEntities())
{
GangMemberBio bio = context.GangMemberBios.First(P =>
P.id == this.id);
bio = this; //this does not work.
context.SaveChanges();
}
//If the top code is successfully completed then the
transaction will be commited
//if not this line will be skipped and execution will be
given to the catch block
scope.Complete();
}
catch
{
}
}
Edit Idea 1 I was thinking I could create a context object on my wpf
window itself and then bind the dataform to my gangmemberbio object
retrieved from this context. Then when I call save changes nothing else
needs to be done. I heard that having a datacontext in memory is bad
though.. Or is it just bad if I use it outside the context of a using
statement?

No comments:

Post a Comment