user2202098
user2202098

Reputation: 860

Entity Framework. Violation of UNIQUE KEY constraint

I am creating a list of objects and adding them to my DbContext, then saving them. The problem is I added a unique constraint to the database to stop objects with duplicate data.

Because the error is thrown on SaveChanges, I could try save each object individually and catch the error. Is that a poor solution and is there a better way to handle it ?

    using (FinanceDBContext financeDBContext = new FinanceDBContext())
    {
        foreach (var item in priceList)
        {
            item.Apimapping = null;
            financeDBContext.Price.Add(item);
        }

        financeDBContext.SaveChanges();
    }

My Price object

public partial class Price
{
    public int PriceId { get; set; }
    public decimal LastPrice { get; set; }
    public decimal Bid { get; set; }
    public decimal Ask { get; set; }
    public DateTime DateCreated { get; set; }
    public int? ApimappingId { get; set; }

    public Apimapping Apimapping { get; set; }
}

Upvotes: 3

Views: 2490

Answers (1)

Mujahid Daud Khan
Mujahid Daud Khan

Reputation: 2071

First check for duplicates in provide list

var distinctBids = priceList.Select(p => p.Bid).ToList();
if (priceList.Count != distinctBids.Count())
    return BadRequest(); // even the provided list have duplicates;

Check for duplicates for input values

if (context.Price.Any(e=> distinctBids.Contains(e.Bid)))
    return BadRequest(); // check for duplicates in database

after that its safe to insert values

// Now its safe to add new prices;
foreach (var item in priceList)
{
    item.ApimappingId = null;
    context.Employees.Add(item);
}
context.SaveChanges();

you will also need to put all of above statements in one traction as described here

Upvotes: 4

Related Questions