Reputation: 549
I have this relationship between two entities:
A symbol (= exchange definition) references a security:
public partial class Symbol : BaseDto
{
...
private int _SecurityId;
/// <summary>
/// Gets or sets the SecurityId
/// </summary>
public int SecurityId { get { return this._SecurityId; } set { this.SetProperty(ref this._SecurityId, value); } }
...
public virtual Security Security { get; set; }
}
I want to do the following:
Steps 1 and 2 work fine. However, on step 3 the EF wants to insert the already inserted security a second time and a key violation exception is thrown.
Any idea why EF does not recognize that the security was alredy inserted into the database? The security's Id identity value is set correctly.
Here some code.
Snippet from unit test where I call the repositories to save the entities and where I udpate the symbol with the saved security:
securityAggregate = securityRepository.AddSecurityAsync(securityAggregate).Result;
symbolAggregate.State.Security = securityAggregate.State;
symbolAggregate = symbolRepository.AddSymbolAsync(symbolAggregate).Result;
This is the symbol repository where the exception occurs, because EF tries to insert the security a second time:
public async Task<SymbolAggregate> AddSymbolAsync(SymbolAggregate Symbol)
{
var SymbolAggregate = await Task.Run<SymbolAggregate>(
() =>
{
var addedSymbol = this.dbContext.Symbols.Add(Symbol.State);
this.dbContext.SaveChanges();
return new SymbolAggregate { State = addedSymbol };
};
return SymbolAggregate;
}
Thank you!
Upvotes: 0
Views: 67
Reputation: 12757
Perhaps the reason for this behaviour is that securityAggregate.State
is disconnected from dbContext
. Issue and various solutions are described in Julie Lerman blog in details. You need to either use foreign key to bind symbol and security together or perform Attach()
in order to context to recongnize existing entity instead of trying to add entire object graph:
this.dbContext.Securities.Attach(Symbol.State.Security);
var addedSymbol = this.dbContext.Symbols.Add(Symbol.State);
this.dbContext.SaveChanges();
Upvotes: 1