dotnet / dotnet/efcore

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

Open
#27,038 2 comments 0 reactions 1 assignee Claimed by @AndriySvyryd View on GitHub
area-model-building customer-reported
Dominant language
C#
Stars
14.8k
Forks
3.4k
PR merge metrics
PR metrics pending

Description

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.

```csharp
//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 Databases => Set();

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

```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.