I have this simple piece of code:
MyObjectContext db = new MyObjectContext();
Person new_person = new Person() {
/* some data, which does not satisfy
the constraints of unique key */
};
db.Person.AddObject(new_person);
db.SaveChanges();
In MSSQL database table I have some unique key in Person table.
When I try to add new_person object, which cannot be added because of unique restrictions, database returns an error, as expected, but In further work MyObjectContext acts, like those insertings has been applied by DB. Like it didn`t hear an error. Only App restart helps to refresh MyObjectContext with actual data.
How to get ObjectContext notified about the error, returned from database, after trying to perform INSERT?
UPD: Thank you for your answers.
When I try to AddObject with duplicate unique key, I get this:
Server Error in '/' Application.
Violation of UNIQUE KEY constraint 'IX_Person'. Cannot insert duplicate key in object 'dbo.Person'.
The statement has been terminated.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Violation of UNIQUE KEY constraint 'IX_Person'. Cannot insert duplicate key in object 'dbo.Person'.
The statement has been terminated.
Source Error:
Line 34:
Line 35: db.Person.AddObject(new_person);
>Line 36: db.SaveChanges();
Line 37:
Line 38: return Json(new ViewPerson(new_person));
Source File: C:\DEV\MyProject\Controllers\PersonController.cs Line: 36
Stack Trace:
[SqlException (0x80131904): Violation of UNIQUE KEY constraint 'IX_Person'. Cannot insert duplicate key in object 'dbo.Person'.
The statement has been terminated.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +2073550
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +5064508
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning() +234
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +2275
System.Data.SqlClient.SqlDataReader.ConsumeMetaData() +33
System.Data.SqlClient.SqlDataReader.get_MetaData() +86
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +311
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) +987
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) +162
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +32
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +141
System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +12
System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) +10
System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator, EntityConnection connection, Dictionary`2 identifierValues, List`1 generatedValues) +8167912
System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter) +267
After that in next request to server I get the exception in second line of this code:
Category some_category = MyEntitiesHelper.db.Category.Single(c => c.ID == 1);
Person some_person = some_category.Person.SingleOrDefault(p => p.UniqueID == "uniqueKey");
System.InvalidOperationException:{“Sequence contains more than one matching element”}
This happenned, because (I checked during debug session), in some_category.Person there was another person with duplicate uniqueKey, which shouldn’t be there, because it didn`t go to database, because while inserting, database returned an error.
Duplicate person object had ID = 0.
By the way, ObjectContext object is created like this:
public static class MyEntitiesHelper
{
private static MyObjectContext _db;
public static MyObjectContext db
{
get
{
if (_db == null) _db = new MyObjectContext();
return _db;
}
}
}
New instance is being created for every request, or it isn`t? Is this a good approach?
The question remains the same: how to prevent “Sequence contains more than one matching element” exception, while trying
Person some_person = some_category.Person.SingleOrDefault(p => p.UniqueID == "uniqueKey");
There is second Person object with duplicate uniqueKey attached to objectcontext, which shouldn`t be there.
How you can say that objectContext works like everything gone fine? You execute another query or you just using a navigation property that uses this new Person object? like
When you call AddObject you obviously attach the entity to the context and it remains even if SaveChanges goes wrong, but it can’t be possible that query another time the database after that could retrieve this new object.
However if you use a navigation property like the example above you don’t necessary query the database and you could see the new person like if it is stored, anyway you should put some more code to explain better what is you problem