简体   繁体   English

实体框架:更新具有 IEnumerable 属性的实体时出错。 'Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException'

[英]Entity Framework: Error updating an Entity with IEnumerable property. 'Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException'

I'm working on my first webapi in ASP.NET Core.我正在 ASP.NET Core 中开发我的第一个 webapi。 I have two entities:我有两个实体:

public class Event : Entity
{
    private ISet<Ticket> _tickets = new HashSet<Ticket>();
    public string Name { get; protected set; }
    public string Description { get; protected set; }
    public DateTime StartDate { get; protected set; }
    public DateTime EndDate { get; protected set; }
    public DateTime CreatedAt { get; protected set; }
    public DateTime UpdatedAt { get; protected set; }
    public IEnumerable<Ticket> Tickets => _tickets;

    //.....

     public void AddTickets(int amount, decimal price)
    {
        var seating = _tickets.Count + 1;
        for (var i = 0; i < amount; i++)
        {
            _tickets.Add(new Ticket(this, seating, price));
            seating++;
        }
    }
 }

  public class Ticket : Entity
{
    public Guid EventId { get; protected set; }
    public decimal Price { get; protected set; }
    //... and other properties
}

When I'm trying to create new event and assign tickets to it:当我尝试创建新活动并为其分配门票时:

public class EventController : Controller
{
   [HttpPost]
    public async Task<IActionResult> AddEvent([FromBody] CreateEventCommand createEventCommand)
    {
        createEventCommand.Id = Guid.NewGuid();
        await _eventService.AddAsync(createEventCommand.Id,
            createEventCommand.Name,
            createEventCommand.Description,
            createEventCommand.StartDate,
            createEventCommand.EndDate);

        await _eventService.AddTicketAsync(createEventCommand.Tickets,
            createEventCommand.Price,
            createEventCommand.Id);

        return Created($"/events/{createEventCommand.Name}", null);
        
    }
 }
 
 public class EventService : IEventService
 {
            public async Task AddAsync(Guid id, string name, string description, DateTime startDate, DateTime endDate)
    {
        var @event = await _eventRepository.GetAsync(id);
        if(@event != null)
        {
            throw new Exception($"Event with this id: {@event.Id} already exist");
        }

        var eventToAdd = new Event(id, name, description, startDate, endDate);
        await _eventRepository.AddAsync(eventToAdd);
    }

    public async Task AddTicketAsync(int amount, decimal price, Guid eventId)
    {
        var @event = await _eventRepository.GetAsync(eventId);
        if (@event == null)
        {
            throw new Exception($"Event with this id: {@event.Id} already exist");
        }

        @event.AddTickets(amount, price);
        await _eventRepository.UpdateAsync(@event);

    }
  }

 public class EventRepository : IEventRepository
 {
    public async Task AddAsync(Event @event)
    {
        _context.Events.Add(@event);
        await _context.SaveChangesAsync();
    }
    
     public async Task UpdateAsync(Event @event)
    {
        _context.Events.Update(@event);
        await _context.SaveChangesAsync();
    }
 }  

The query which is executed on Tickets table is在 Tickets 表上执行的查询是

  UPDATE [Tickets] SET [EventId] = @p700, [Price] = @p701, [PurchasedAt] = @p702, [Seating] = @p703, [UserId] = @p704, [Username] = @p705
  WHERE [Id] = @p706;
  SELECT @@ROWCOUNT;

After that It throws an exception:之后它抛出异常:

Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException: Database operation expected to affect 1 row(s) but actually affected 0 row(s). Data may have been modified or deleted since entities were loaded.

My question is: shouldn't it be INSERT queries instead of UPDATE in this case and what could be a reason of concurrency problem in this case?我的问题是:在这种情况下,它不应该是 INSERT 查询而不是 UPDATE,在这种情况下并发问题的原因可能是什么? I'm new to .NET and concurency in general, would be grateful for any help.我是 .NET 和并发的新手,如果有任何帮助,我将不胜感激。

In your AddTicketAsync method you retrieve an attached entity of your Event object.在您的 AddTicketAsync 方法中,您检索事件对象的附加实体。

You should be able to update it by calling your AddTickets method following by a save changes.您应该能够通过在保存更改之后调用 AddTickets 方法来更新它。

 @event.AddTickets(amount, price);
 _eventRepository.your_context.SaveChangesAsync();

In this way you will save the state of your updated Event Entity通过这种方式,您将保存更新的事件实体的状态

You got a concurrency error because your are trying to update an attached entity.您遇到并发错误,因为您正在尝试更新附加实体。 The following post could help you How to update record using entity framework core?以下帖子可以帮助您如何使用实体框架核心更新记录?

暂无
暂无

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

相关问题 Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException - Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException OracleModificationCommandBatch.Consume():Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException - OracleModificationCommandBatch.Consume() : Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException Asp.net 核心 Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException: - Asp.net Core Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException: 实体框架6:DbUpdateConcurrencyException - Entity Framework 6: DbUpdateConcurrencyException 抛出异常:System.Private.CoreLib.ni.dll中的&#39;Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException&#39; - Exception thrown: 'Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException' in System.Private.CoreLib.ni.dll Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException:'数据库操作预计会影响 1 行,但实际上会影响 2 行 - Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException: 'Database operation expected to affect 1 row(s) but actually affected 2 row(s) 实体框架代码中的DbUpdateConcurrencyException优先 - DbUpdateConcurrencyException in Entity Framework Code First 使用实体框架更新实体的单个属性时出错 - Error in updating single property of an entity using Entity Framework 在EntityFrameworkCore中更新稍微复杂的实体 - Updating a slightly complex entity in EntityFrameworkCore 实体框架和IEnumerable - Entity Framework and IEnumerable
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM