skip to Main Content

I’ve faced the problem with using ExecuteDelete in the abstract generic class. Can someone explain in what cases ExecuteDelete and ExecuteUpdate cannot be used? Tagret framework is set to .Net 7

Here is how my code looks:

using Microsoft.EntityFrameworkCore;

namespace ProjectX.Common.Repositories;

public abstract class BaseRepository<T, V> : IRepository<T, V>
where T : Entity
where V : struct
{
protected readonly DbContext _context;

public BaseRepository(DbContext context)
{
    _context = context;
}

public virtual async Task<bool> DeleteAsync(T entity, CancellationToken cancellationToken = default)
{
    var deleted = await _context.Set<T>()
                 .Where(t => t.Id.Equals(entity.Id))
                 .ExecuteDeleteAsync(); // Here is the problem. This method cannot be found. Target Framework is .Net 7 and EF Core version is 7.0.7

    return deleted > 0;
}
}

EF Core version: 7.0.7
Database provider: Microsoft.EntityFrameworkCore.SqlServer
Target framework: NET 7.0
IDE: Visual Studio 2022 latest version

2

Answers


  1. Chosen as BEST ANSWER

    It was missing package reference to Microsoft.EntityFrameworkCore.Relational


  2. Please see:
    https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-7.0/whatsnew#inheritance-and-multiple-tables

    "Adding a filter to the query often means the operation will fail with both the TPC and TPT strategies. This is again because the rows may need to be deleted from multiple tables. For example, this query:

    await context.Posts.Where(p => p.Author!.Name.StartsWith("Arthur")).ExecuteDeleteAsync();
    

    fails when using TPC or TPT."

    Issue #10879 tracks adding support for automatically sending multiple commands in these scenarios. Vote for this issue if it’s something you would like to see implemented.

    tl;dr
    ExecuteUpdate/Delete can only act on a single table and generic entity may have relations to other tables when working with TPC/TPT mapping strategies.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search