Entity Framework. Violation of UNIQUE KEY constraint

.net-core c# entity-framework entity-framework-core

Question

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; }
}
1
0
2/11/2018 1:24:53 PM

Accepted Answer

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

2
2/11/2018 1:17:52 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow