We have a model with an entity called "Connection". The key is taken from an oracle sequence we have specified in the model.
Code: Select all
The code is like this. The error occurs when "if (connection == null)" is true and we call Create and ConnectAO directly after eachother.Error in GetPortfolioIdByAO:
System.InvalidOperationException: The following objects have not been refreshed because they were not found in the store:
'EntitySet=ConnectionSet;CONNECTION_ID=186'.
at System.Data.Objects.ObjectContext.RefreshEntities(RefreshMode refreshMode, IEnumerable collection)
at System.Data.Objects.ObjectContext.Refresh(RefreshMode refreshMode, Object entity)
at Forsmark.BusinessProcesses.UH.BusinessComponents.Portfolio.PortfolioLogic.ConnectAO(Int32 portfolioId, Int32 aroNr)
at Forsmark.BusinessProcesses.UH.BusinessComponents.Portfolio.PortfolioLogic.GetPortfolioIdByAO(Int32 aroNr)
at Forsmark.BusinessProcesses.UH.BusinessComponents.Portfolio.BC_Portfolio.GetPortfolioIdByAO(Int32 aroNr)
Code: Select all
public int GetPortfolioIdByAO(int aroNr)
{
using (var context = new PortfolioEntities(this.connectionString))
{
var connection = context.ConnectionSet.FirstOrDefault(x => x.ARO_NR == aroNr);
int portfolioId;
if (connection == null)
{
portfolioId = this.Create();
this.ConnectAO(portfolioId, aroNr);
}
else
{
portfolioId = connection.CONNECTION_ID;
}
return portfolioId;
}
}
public void ConnectAO(int portfolioId, int aroNr)
{
using (var context = new PortfolioEntities(this.connectionString))
{
var connection = context.ConnectionSet
.First(x => x.CONNECTION_ID == portfolioId);
if ((connection.ARO_NR ?? aroNr) != aroNr)
{
throw new Exception("Portfolio redan kopplad till annan arbetsorder!");
}
connection.ARO_NR = aroNr;
try
{
context.SaveChanges();
}
catch (OptimisticConcurrencyException)
{
context.Refresh(RefreshMode.ClientWins, connection);
context.SaveChanges();
}
}
}
public int Create()
{
using (var context = new PortfolioEntities(this.connectionString))
{
var connection = new Connection();
context.AddToConnectionSet(connection);
context.SaveChanges();
return connection.CONNECTION_ID;
}
}