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 7939591
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 3, 20262026-06-03T23:08:52+00:00 2026-06-03T23:08:52+00:00

I’m having a rather strange issue with Entity Framework 4.3 in my MVC application.

  • 0

I’m having a rather strange issue with Entity Framework 4.3 in my MVC application. I’m using a Unit of Work wrapper around DbContext, and in my MVC application I use Unity to pass this UOW to my repositories, and repositories to controllers. I’ve registered the UOW type with the HierarchicalLifetimeManager.

When I try to persist an entity to the database that raises an error, e.g. the database throws a UNIQUE constraint violation, the entity is kept inside EF’s ObjectStateManager. So when I go back in my application to fix the error and save the new entity (without errors), EF first tries to add the old and invalid object again, thus failing with the same error.

What am I missing here? I believe that the invalid object should be completely forgotten by EF and that this would be done automatically. But it’s clearly not the case.

To add objects to DbContext in order to persis them, the following command gets called (where base is the DbContext):

base.Set<TEntity>().Add(objectToPersist);

And to commit the changes to the database, I call:

base.SaveChanges();

Which throws the error.

  • 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-03T23:08:53+00:00Added an answer on June 3, 2026 at 11:08 pm

    I believe that the invalid object should be completely forgotten by EF
    and that this would be done automatically. But it’s clearly not the
    case.

    Right, that’s not the case and I’ve never heard that entities would be detached from the context automatically when an exception occured.

    There are basically two options to deal with the problem. I show a simple model with your example of a unique key constraint violation:

    public class Customer
    {
        // so we need to supply unique keys manually
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int Id { get; set; }
        public string Name { get; set; }
    }
    
    public class MyContext : DbContext
    {
        public DbSet<Customer> Customers { get; set; }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            Database.SetInitializer(new DropCreateDatabaseAlways<MyContext>());
    
            using (var ctx = new MyContext())
            {
                var customer = new Customer { Id = 1, Name = "X" };
                ctx.Customers.Add(customer);
                ctx.SaveChanges();
            }
            // Now customer 1 is in database
    
            using (var ctx = new MyContext())
            {
                var customer = new Customer { Id = 1, Name = "Y" };
                ctx.Customers.Add(customer);
    
                try
                {
                    ctx.SaveChanges();
                    // will throw an exception because customer 1 is already in DB
                }
                catch (DbUpdateException e)
                {
                    // customer is still attached to context and we only
                    // need to correct the key of this object
                    customer.Id = 2;
                    ctx.SaveChanges();
                    // no exception
                }
            }
        }
    }
    

    The above is the prefered solution: Correct the object which is attached to the context.

    If you need – for whatever reason – to create a new object you must detach the old object from the context. That object is still in state Added and EF will try to save the object again when you call SaveChanges leading to the same exception as before.

    Detaching the old object would look like this:

                try
                {
                    ctx.SaveChanges();
                    // will throw an exception because customer 1 is already in DB
                }
                catch (DbUpdateException e)
                {
                    ctx.Entry(customer).State = EntityState.Detached;
                    // customer is now detached from context and
                    // won't be saved anymore with the next SaveChanges
    
                    // create new object adn attach this to the context
                    var customer2 = new Customer { Id = 2, Name = "Y" };
                    ctx.Customers.Add(customer2);
                    ctx.SaveChanges();
                    // no exception
                }
    

    This procedure can be tricky if relationships are involved. For example if customer has a relationship to a list of orders, detaching the customer object will delete references between customer and its orders if the orders are attached to the context as well. You have to reestablish the relationships with the new customer2.

    Therefore I’d prefer to modify the attached object to put it into correct state. Or let the application crash because such constraint violations usually indicate bugs in the code or – in a multiuser environment – should be handled with proper optimistic concurrency checks.

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

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
We're building an app, our first using Rails 3, and we're having to build
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am reading a book about Javascript and jQuery and using one of the
I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
We are using XSLT to translate a RIXML file to XML. Our RIXML contains
I have an MVC Razor view @{ ViewBag.Title = Index; var c = (char)146;
I'm having trouble keeping the paragraph square between the quote marks. In firefox the

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.