簡體   English   中英

實體框架:更新具有 IEnumerable 屬性的實體時出錯。 'Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException'

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

我正在 ASP.NET Core 中開發我的第一個 webapi。 我有兩個實體:

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
}

當我嘗試創建新活動並為其分配門票時:

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

在 Tickets 表上執行的查詢是

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

之后它拋出異常:

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.

我的問題是:在這種情況下,它不應該是 INSERT 查詢而不是 UPDATE,在這種情況下並發問題的原因可能是什么? 我是 .NET 和並發的新手,如果有任何幫助,我將不勝感激。

在您的 AddTicketAsync 方法中,您檢索事件對象的附加實體。

您應該能夠通過在保存更改之后調用 AddTickets 方法來更新它。

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

通過這種方式,您將保存更新的事件實體的狀態

您遇到並發錯誤,因為您正在嘗試更新附加實體。 以下帖子可以幫助您如何使用實體框架核心更新記錄?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM