简体   繁体   English

实体框架。 违反UNIQUE KEY约束

[英]Entity Framework. Violation of UNIQUE KEY constraint

I am creating a list of objects and adding them to my DbContext , then saving them. 我正在创建对象列表并将其添加到我的DbContext ,然后保存它们。 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. 因为错误是在SaveChanges上引发的,所以我可以尝试分别保存每个对象并捕获错误。 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 我的Price对象

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; }
}

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 你也需要把所有以上陈述的一个牵引描述这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM