dotnet / efcore

EF Core is a modern object-database mapper for .NET. It supports LINQ queries, change tracking, updates, and schema migrations.
https://docs.microsoft.com/ef/
MIT License
13.73k stars 3.17k forks source link

Misleading exception when a class used as entity does not have any properties #27038

Open Brar opened 2 years ago

Brar commented 2 years ago

When trying to query a DbContext with an entity that doesn't have any properties you get an InvalidOperationException that says: "Sequence contains no elements" before the query even hits the database.

While such an empty class is obviously useless, this problem easily happens when you start putting things together. In a somewhat complex project the misleading exception can cause quite a headache when you try to find out what's going on.

Theoretically the example below could "just work" (mapping nothing to the empty Database class) but as an alternative it could possibly throw a more helpful exception. The fact that ToListAsync() bothered that a sequence contains no elements was very misleading in that case.

//dotnet new console
//dotnet add package Microsoft.EntityFrameworkCore.SqlServer --version 6.0.1

using Microsoft.EntityFrameworkCore;

using var ctx = new MyDbContext();

var emptyClasses = await ctx.Databases.ToListAsync();

public class Database { }
public class MyDbContext : DbContext
{
    public IQueryable<Database> Databases  => Set<Database>();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
            modelBuilder.Entity<Database>(e =>
            {
                e.HasNoKey();
                e.ToView("databases", "sys");
            });
    }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=MyEFDemoDb;Trusted_Connection=True");
    }
}
roji commented 2 years ago

Thinking about this again, IIRC databases typically don't allow creating tables with no columns, so I'm not sure this can be made to "work". However, the exception is indeed quite cryptic - we should throw something better (possibly in model validation).

Brar commented 2 years ago

IIRC databases typically don't allow creating tables with no columns, so I'm not sure this can be made to "work"

Most certainly not for migrations but the empty class might map to a table that only has columns we aren't interested in (yet) and for this reason don't want to map (yet).