开发者

Problem updating an Entity

I have a problem when updating an entity (User) in my application.

The entity is located in session when the user has been logged. So I made it:

Dim u as User = (From x in ctx.Users).First()
Session("user") = u

Ok, no problem yet.

But when I need to change the user:

Dim u as User = Ctype(Session("User"),User)
u.name = "new name"
ctx.Users.ApplyCurrentValues(u)

I got the follow error:

An object with a key that matches the key of the supplied object could not be found in the ObjectStateManager.开发者_JS百科 Verify that the key values of the supplied object match the key values of the object to which changes must be applied.


First example cannot work until you do this:

Dim u as User = Ctype(Session("User"),User)
u.name = "new name"
(From x in ctx.Users).First()
ctx.Users.ApplyCurrentValues(u)
ctx.SaveChanges

ApplyCurrentValues only take values from passed object and copies them to the same object type which must be loaded and attached to the context.

Second example shown by @Mlantosca cannot work because you are storing entity in session and you didn't detach it. To make it work you must use:

Dim u as User = (From x in ctx.Users).First()
ctx.Detach(u)
Session("user") = u


you might want to try this:

ctx.Users.Attach(User);
ctx.ObjectStateManager.ChangeObjectState(User, EntityState.Modified);
ctx.SaveChanges();

this is the style I use when I update existing entities in EF

-Michael

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜