EF - How do I attach a "EntityKey" object for savechanges

  • Thread starter Thread starter RichB
  • Start date Start date
R

RichB

I have created an Entity Framework Context from a database which has a
location ---- country relationship.

As the country table is static, I am creating the Country within my code
using the EnitiyKey as follows:

country.EntityKey = new EntityKey("NearlyThereEntities1.Country",
"countryCode", countryCode);

I then add to the Location as follows:

Location.Country = country;


However when I try to add the Location I get the following error:

The object cannot be added to the ObjectStateManager because it already has
an EntityKey. Use ObjectContext.Attach to attach an object that has an
existing key.

I have tried MyObjectContext.Attach(country); But don't really understand
what the attach method is doing i.e. how to build the relationship between
the Location and country.

I wonder if someone could give me some pointers in how to resolve this.
 
Hello Richs,

Attach() method is used to attach an object to an ObjectContext. The object
attached is usually retrieve from another place, like remote method call or
WCF service, or deserialized from file and so on. These objects are
supposed to have entity keys. AddObject() is supposed to add a new created
object to the ObjectContext. So we will see that prompt error message.

Actually, to add related objects, we can call Attach on ObjectContext to
attach object to the object context. Do this when the object already exists
in the data source but is currently not attched to the context. For more
information, see,
http://msdn.microsoft.com/en-us/library/bb896271.aspx
http://msdn.microsoft.com/en-us/library/bb896245.aspx


Best regards,
Ji Zhou
Microsoft Managed Newsgroup Support Team
 
Thanks,

I had read those articles, but haven't really grasped the difference between
Add, AddObject, Attach and AttachTo and whether I always need to use one of
these to create a complex object in the ObjectContext.

I am trying to create a Venue with
- one address
- many categories (corresponding to finite set of categories in a table)

I was trying to do it as follows:

Venue ven= new Venue();
ven.Address = new Address(){//set address criteria}
ven.Address.Country.EntityKey = GetCountryEntityKey(country);
ven.Category = new Category();
ven.Category.EntityKey = GetCategoryEntityKey();

context.Add(ven);

context.SaveChanges(ven);


My original understanding (which would appear to be incorrect) was that
adding venue would add the associated objects too. What do I need to do to
ensure all of the objects are added to the object context and when they are
associated are they automatically mapped to the corresponding ven object?

Is there a good tutorial somewhere (or book) which will answer these
questions? (The book I was reading seemed to imply my original understanding)
 
Back
Top