How to add entity with existing attached to it -


i want add entity payment object, containing existing currency object ef database:

public payment() {    int id {get;set;}    public int value {get;set;}    public currency selectedcurrency{get;set;} }  public currency() {     int id {get;set;}     string name; } 

suppose have existing currency attached new entity payment(). when add such entity payment(), error appears

violation of primary key constraint 'pk_dbo.currency'. cannot insert duplicate key in object 'dbo.mwbecurrency'. duplicate key value (gbp).\r\nthe statement has been terminated."}

how add higher-level entity attached existing lower-level entity?

my code adding entity is:

public virtual tentity add(tentity entity)         {             return dbset.add(entity);         }  public void savechanges()         {             context.savechanges();                     } 

i suspect retrieved currency different instance 1 retrieved payment , did :

payment.currency = retrievedcurrency; 

therefore, payment context things currency new object , tries persist it. since exists, getting primary key violation.

if want persist payment correctly, add following lines:

if (payment.currency != null && payment.currency.id != 0)  {     context.entry(payment.currency).state = entitystate.unchanged; } 

although cleaner if retrieved payment , currency same context, can persist them appropriately.


Comments

Popular posts from this blog

shopping cart - Page redirect not working PHP -

php - How to modify a menu to show sub-menus -

python - Installing PyDev in eclipse is failed -