Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BulkRead does not work for views #1430

Open
arjensteinhauer opened this issue Mar 6, 2024 · 1 comment
Open

BulkRead does not work for views #1430

arjensteinhauer opened this issue Mar 6, 2024 · 1 comment

Comments

@arjensteinhauer
Copy link

Hi, when I try to use BulkRead to read entities from a SQL Server view, the method throws an exception 'Entity does not contain a table name'. When I look into the code, I think the IEntityType.GetTableName() form Entity Framework Core is used. This method indeed will return null for entities mapped to SQL views. IEntityType.GetViewName() should probably be used instead.

Is it possible to add support to BulkExtensions.BulkRead to read entities from a view? That would be great!

Versions being used by me at the moment:

  • Microsoft.EntityFrameworkCore version 7.0.11
  • EFCore.BulkExtensions version 7.1.6

entity definition:

public class MyViewItem
{
    public long Id { get; set; }
    
    public int TenantId { get; set; }
    
    [Required]
    [MaxLength(100)]
    public string Description { get; set; }
}

DbContext:

public class MyContext : DbContext
{
    public DbSet<MyViewItem> MyViewItems { get; set; }
    
    public MyContext(DbContextOptions<MyContext> options) : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<MyViewItem>(entity =>
        {
            entity.HasKey(item => new { item.TenantId, item.Id });
            entity.ToView("MyView");
        });
    }
}

Code to read (which throws the exception):

public async Task<IEnumerable<MyViewItem>> ReadViewItems(List<long> ids)
{
    var tenantId = 1;
    var entities = ids
        .Select(id => new MyViewItem { Id = id, TenantId = tenantId })
        .ToList();

    using (var context = _contextFactory.Create())
    {
        await context.BulkReadAsync(entities, config =>
        {
            config.UpdateByProperties = new List<string> { nameof(MyViewItem.TenantId), nameof(MyViewItem.Id) };
        }).ConfigureAwait(false);

        return entities;
    }
}

SQL Server view

CREATE OR ALTER VIEW [MyView] AS
SELECT [TenantId]
     , [Id]
     , [Description]
FROM   [MyTable]
@borisdj
Copy link
Owner

borisdj commented Mar 20, 2024

Will look into it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants