为什么不能使用EF核心保存对相关数据的更新?

时间:2018-11-18 19:31:04

标签: c# entity-framework asp.net-web-api asp.net-core entity-framework-core

我正在尝试在控制器中实现PUT方法,该控制器将使用新的Pricelist实体和对现有Offer实体的更改来更新名为Offer的实体。

当我尝试运行以下代码时,出现错误

  

集合已修改;枚举操作可能无法执行。

我不确定自己在做什么错。有什么想法吗?

型号:

public class Offer : BaseEntity
{
    public PriceList PriceList { get; set; }
    public int PriceListId { get; set; }

    public Product Product { get; set; }
    public int ProductId { get; set; }

    public decimal Price { get; set; }
    public bool IsActive { get; set; }
}

public class PriceList : BaseEntity
{
    public string Name { get; set; }

    public List<Customer> Customers { get; set; }
    public List<Offer> Offers { get; set; }

    public bool IsActive { get; set; }
}

呼叫代码:

// PUT: api/PriceLists/5
[HttpPut("{id}")]
public async Task<IActionResult> PutPriceList([FromRoute] int id, 
        [FromBody] PriceListViewModel priceList)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    if (id != priceList.Id)
    {
        return BadRequest();
    }

    var priceListFromDb = await _context.PriceLists.Where(x => x.Id == id).Include(x => x.Offers).FirstOrDefaultAsync();

    if (priceListFromDb == null)
    {
        return BadRequest();
    }

    priceListFromDb.Name = priceList.Name;

    // Check if incoming offer is already in pricelist, in that case update. If not, create and add a new Offer.
    foreach (var item in priceListFromDb.Offers)
    {
        foreach (var newItem in priceList.Offers)
        {
            if (item.Id == newItem.OfferId)
            {
                item.ProductId = newItem.ProductId;
                item.Price = newItem.Price;
            }
            else if (newItem.OfferId == null || newItem.OfferId <= 0)
            {
                var newOffer = new Offer
                        {
                            ProductId = newItem.ProductId,
                            Price = newItem.Price,
                            IsActive = true,
                            PriceListId = id
                        };
                priceListFromDb.Offers.Add(newOffer);
            }
        }
    }

    _context.Entry(priceListFromDb).State = EntityState.Modified;

    try
    {
        await _context.SaveChangesAsync();
    }
    catch (DbUpdateConcurrencyException)
    {
        if (!PriceListExists(id))
        {
           return NotFound();
        }
        else
        {
            throw;
        }
    }

    return NoContent();
}

0 个答案:

没有答案