none
DBContext - Modified Parent and newly Added Child Items RRS feed

  • Question

  • I have a parent entity IMZ which has a child entity IMZCalc. When I load an IMZ entity the sub items get loaded too. In the GUI I want the user to be able to modify both the parent and the child items. However when I modify the parent entity and in the same action create new child items, a new parent entity is created in the context. So when I call DBContext.SaveChanges() I get an error "Cannot insert duplicate key in object. ..."

    How can I solve this?

    Procedure:

    If it's a new entity I add it else I set the entity state. Below the 2 functions I'm using:

    public void Add<TEntity>(TEntity entity) where TEntity : class
    {
        if (entity == null) { throw new ArgumentNullException("entity"); }
        DbContext.Set<TEntity>().Add(entity);
    }
    
    public void SetEntityState<TEntity>(object oldKeyValue, TEntity newEntity, EntityState state) where TEntity : class
    {
        var oldEntity = this.GetByKey<TEntity>(oldKeyValue);
    
        if (oldEntity == null) DbContext.Entry<TEntity>(newEntity).State = state;
        else
        {
            DbContext.Entry<TEntity>(oldEntity).CurrentValues.SetValues(newEntity);
            DbContext.Entry<TEntity>(oldEntity).State = state;
        }
    }


    • Edited by Syslock Monday, August 19, 2013 12:32 PM
    Monday, August 19, 2013 10:07 AM

Answers

  • Hello,

    Welcome toMSDN Support Forum.

    From your description, I notice the issue you are experiencing is that it throws an exception while you call DBContext.SaveChanges().

    If I have misunderstood, please let me know.

    I notice that the exception is “Cannot insert duplicate key in object”.

    As far as I know that it may be caused by that there is the same record existing in your database already.

    So I suggest that you can check it that if the record exists before adding a new object.

    If it is possible, could you please share your table structure and more codes as the structure of your Entity Framework.

    With these information we can help you better.

    I look forward to hearing from you.

    Best Regards.


    <THE CONTENT IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED>
    Thanks
    MSDN Community Support

    Please remember to "Mark as Answer" the responses that resolved your issue. It is a common way to recognize those who have helped you, and makes it easier for other visitors to find the resolution later.

    Tuesday, August 20, 2013 8:41 AM
    Moderator

All replies

  • Hello,

    Welcome toMSDN Support Forum.

    From your description, I notice the issue you are experiencing is that it throws an exception while you call DBContext.SaveChanges().

    If I have misunderstood, please let me know.

    I notice that the exception is “Cannot insert duplicate key in object”.

    As far as I know that it may be caused by that there is the same record existing in your database already.

    So I suggest that you can check it that if the record exists before adding a new object.

    If it is possible, could you please share your table structure and more codes as the structure of your Entity Framework.

    With these information we can help you better.

    I look forward to hearing from you.

    Best Regards.


    <THE CONTENT IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED>
    Thanks
    MSDN Community Support

    Please remember to "Mark as Answer" the responses that resolved your issue. It is a common way to recognize those who have helped you, and makes it easier for other visitors to find the resolution later.

    Tuesday, August 20, 2013 8:41 AM
    Moderator
  • Hello

    As stated above the parent entity IMZ get's modified and thus gets inserted into the context with EntityState =  modified. Also a new child entity IMZCalc gets added to IMZ.IMZCalc collection which gets inserted into the context with EntityState = Added. However with these 2 actions a new IMZ entity gets added to the context automatically. I need to know why and how to prevent this. Because when I call DBContext.SaveChanges() I get an error.

    Wednesday, August 21, 2013 6:08 AM
  • Hello,

    If you can share your code that how you operate the table like below:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    namespace DB_First
    {
        class S2013_08_21_2
        {
            internal void Execute()
            {
                using (TestDataBaseEntities db = new TestDataBaseEntities())
                {
                    Order order = db.Orders.FirstOrDefault();
                    order.OrderName = "Modify001";
                    Console.WriteLine(db.Entry<Order>(order).State.ToString());
                    OrderDetail od = new OrderDetail();
                    od.OrderDetailID = 1;
                    od.OrderDetailCode = "OrderDetailCode001";
                    od.OrderDetailName = "OrderDetailCode001";
                    Console.WriteLine(db.Entry<OrderDetail>(od).State.ToString());
                    order.OrderDetails.Add(od);
                    Console.WriteLine(db.Entry<OrderDetail>(od).State.ToString());
                    db.SaveChanges();
                }
                Console.ReadLine();
            }
        }
    }

    and your table structure.

    I think your problem will get a solution faster.

    If not so, we can only guess and you know that it is inefficient.

    Thanks for your understanding.

    Wednesday, August 21, 2013 11:53 AM