views:

899

answers:

2

Assuming I have a row in the database with a specific id which I know (in my sample below - a symbol with Id = 5), can I create an EntityObject which can be attached to another entity without the need to load it from the database (same scenario is applicable to "DeleteObject" as well, if you think about it...)?

I've tried the following:

UserSpread spread = UserSpread.CreateUserSpread(5, 500000, 1.1m, 1.5m);

EntityKey symbolKey = new EntityKey("Entities.SymbolSet", "Id", 5);

Symbol symbol = new Symbol();
symbol.EntityKey = symbolKey;

// dealingEntities.Attach(symbol);

spread.Symbol = symbol;
Entities.AddToSpreadSet(spread);

I get the following exception on the "AddToSpreadSet()" method:

"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."

If I try to attach the symbol before assigning it to the spread (commented line), I get the following on the "SaveChanges()" method:

"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."

Any ideas?
Thanks,
Nir

+3  A: 

The general approach I use is to just create a stub entity (by setting just the PK) and attach it to the context.

So here is an example:

Category existing = new Category {ID = 7};
ctx.AttachTo("Categories", existing); // Notice no use of EntityKey anywhere


// build a new product
...
product.Category = existing;
ctx.AddToProducts(product);
ctx.SaveChanges();

This works well for building relationships, but there are some caveats when deleting. So should definitely check out my EF tips series for more information. And in particular this one:

Tip 9 - How to delete an object without retrieving it

Hope this helps

Alex

Alex James
Nice! Works like a charm, thanks a lot!Nir.
nirpi
A: 

It is possible to do what you're asking. You'll have to do something like the following:

dealingEntities.symbolReference.EntityKey = new EntityKey("Entities.SymbolSet", "Id", 5);

Does that make sense? I may have your entity names mixed up so ask me if you need further information.