This is a migrated thread and some comments may be shown as answers.

Duplicate key exception when Adding/Updating object with existing references

1 Answer 65 Views
Development (API, general questions)
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
Marcel
Top achievements
Rank 1
Marcel asked on 28 Nov 2016, 10:31 AM

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

1 Answer, 1 is accepted

Sort by
0
Marcel
Top achievements
Rank 1
answered on 06 Dec 2016, 11:46 AM

Any ideas how I can approach this problem?

Tags
Development (API, general questions)
Asked by
Marcel
Top achievements
Rank 1
Answers by
Marcel
Top achievements
Rank 1
Share this question
or