Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7718587
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T03:12:05+00:00 2026-06-01T03:12:05+00:00

I have this simple piece of code: MyObjectContext db = new MyObjectContext(); Person new_person

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-01T03:12:06+00:00Added an answer on June 1, 2026 at 3:12 am

    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

    Person newPerson = someRelatedEntity.Persons.Where(p=>p.PersonID = "uniqueKey").FirstOrDefault();
    

    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

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have this piece of simple code: SimpleDateFormat sqlFormatter = new SimpleDateFormat (YYYY-MM-dd HH:mm:ss);
I have this simple piece of HTML code: <div> <input type=file name=english-file /> </div>
I've wrote this simple piece of code. And I have a slight problem with
I have this piece of simple code. <html> <head> <script type=text/javascript> function changeText() {
I have a very simple little piece of Lua code, which I wrote while
I have this simple code: DateTime date = new DateTime(dateValue); DateTime currentDate = new
I have a simple piece of code that periodically writes data to a fd
I have this simple piece of code in jQuery $(document).ready(function() { $('#switcher').click(function(event) { if
this is a simple piece of code which is suppose to read n numbers
I have this simple html piece of code, whenever I click on any of

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.