Duplicate key exception when Adding/Updating object with existing references

Thread is closed for posting
2 posts, 0 answers
  1. Marcel
    Marcel avatar
    42 posts
    Member since:
    Jan 2014

    Posted 28 Nov 2016 Link to this post

    Hello,

    I am working on a WCF application and have a question about the best approach for adding and updating objects with DataAcess.
    I have the following new dataobject that I want to save, this dataobject is send to a WCF service, so it’s not attached to any context. To Add it I call the Add-method followed by the SaveChanges method on the context (a IUnitOfWork instance).

     

    public class Order
    {
        private int _orderID;
      
        private int _orderTypeID;
     
        private DateTime _orderDate;
     
        private OrderType _orderType;
     
         
        [DataMember]
        public int OrderID
        {
            get { return _orderID; }
            set { _orderID = value; }
        }
         
        [DataMember]
        public int OrderTypeID
        {
            get { return _orderTypeID; }
            set { _orderTypeID = value; }
        }
         
        [DataMember]
        public DateTime OrderDate
        {
            get { return _orderDate; }
            set { _orderDate = value; }
        }
         
        [DataMember]
        public OrderType OrderType
        {
            get { return _orderType; }
            set { _orderType = value; }
        }
    }
     
    public class OrderType
    {
        private int _orderTypeID;
     
        private string _typeName;
     
         
        [DataMember]
        public int OrderTypeID
        {
            get { return _orderTypeID; }
            set { _orderTypeID = value; }
        }
         
        [DataMember]
        public string TypeName
        {
            get { return _typeName; }
            set { _typeName = value; }
        }
    }

     


    When I save this and the OrderType reference is set, the DataAccess layer is trying to add this OrderType again to the database and I receive an SQL exception.

    What is the recommended approach to “tell” the DataAcess layer that it only needs to add the reference objects when they do not exist yet in the database?

    I seen another thread with this qeuestion (http://www.telerik.com/forums/handling-reference-objects-in-the-disconnected-api) but that is an very old thread and I assume there is a much more convenient way to overcome this problem now.

    Regards,

    Marcel

  2. Marcel
    Marcel avatar
    42 posts
    Member since:
    Jan 2014

    Posted 06 Dec 2016 in reply to Marcel Link to this post

    Any ideas how I can approach this problem?

Back to Top