Question

I create a new object and want to attach it to a context like this,

User user = new User();
user.userName=”Kobe”;
context.Attach(user);

An error message appears – “An object with a null EntityKey value cannot be attached to an object context”. If I query out a user object from database and assign it’s EntityKey to the new object, then detach the query result object like this,

User user = (from u in context.Users where u.userID == 1 select u).First();
User newUser = new User();
newUser.userName = “Kobe”;
newUser.EntityKey = user.EntityKey;
context.Detach(user);
context.Attach(newUser);

Another error message appears – “The object cannot be attached because the value of a property that is a part of the EntityKey does not match the corresponding value in the EntityKey.” I really don’t know what the EntityKey is, I searched on the internet and have seen the EntityKey Class in MSDN, but still can’t understand clearly. When the EntityKey created and attached to an object? where can I find it? If I detach the object, why the EntityKey is still exist?

Anyone can help? Thanks in advance!

Was it helpful?

Solution

An EntityKey is an object that is used by the Entity Framework to uniquely identify your object and keep track of it.

When you construct a new object the key properties of your entity are null (or 0). The ObjectContext doesn't know that you're entity exists and doesn't track it yet so there is no entity key.

When you add the object to the context, a temporary key is constructed. After that you can save the changes to your database. This will generate an Insert statement and retrieve the new key from the database, construct the permanent EntityKey and update all the references it has to the temporary key.

Attaching is another story. You attach an entity to the ObjectContext when the object already exists in your database but has no connection to an ObjectContext.

So in your case you should change your code for adding a new entity to:

User user = new User();
user.userName=”Kobe”;

context.Users.Add(user); // Generate a temporary EntityKey
// Insert other objects or make changes
context.SaveChanges(); // Generate an insert statement and update the EntityKey

OTHER TIPS

Think of an EntityKey class as an unique identifier for the entity. Context uses it for various operations like change tracking, merge options etc. If you dont want to specify an entitykey for the new object use context.AttachTo("Users",user) and context would generate entitykey for you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top