Building an EntityObject from an EntityKey without calling a database in the Entity Framework

Assuming I have a row in the database with a specific identifier that I know (in my example below, the character with Id = 5), can I create an EntityObject that can be attached to another object without having to load it from the database (the same scenario applies to "DeleteObject" if you think about it ...)?

I 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 in the AddToSpreadSet () method:

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

, ( ), SaveChanges():

" , , EntityKey, EntityKey."

? ,
Nir

+3
2

, , - - ( PK) .

, :

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();

, . EF. , , :

9 -

,

+3

, . - :

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

? , , , .

+1

Source: https://habr.com/ru/post/1710496/


All Articles