dotnet / dotnet/efcore

InvalidOperationException on collection ThenInclude on keyless entities

Open
#29,788 5 comments 1 reaction 0 assignees View on GitHub
area-query customer-reported
Dominant language
C#
Stars
14.8k
Forks
3.4k
PR merge metrics
PR metrics pending

Description

Right now it doesn't seam possible to do a quite simple _sub-include_, if the containing entity doesn't own a primary key:

```C#
using Microsoft.EntityFrameworkCore;

var dbContext = new DbContext();

Console.WriteLine(dbContext.Set().Include(p => p.User).ThenInclude(u => u.Properties).ToQueryString());

// _Unneccessary_ `System.InvalidOperationException` here!
Console.WriteLine(dbContext.Set().Include(p => p.User).ThenInclude(u => u.Properties).ToQueryString());

// While this one works:
Console.WriteLine(dbContext.Set().Include(p => p.User).ToQueryString());

class KeyedTable
{
public Guid Id { get; set; }
public Guid UserId { get; set; }
public User User { get; set; }
}

class KeylessTable
{
public Guid UserId { get; set; }
public User User { get; set; }
}

class User
{
public Guid Id { get; set; }
public ICollection Properties { get; set; }
}

class UserProperty
{
public Guid Id { get; set; }
public Guid UserId { get; set; }
public User User { get; set; }
}

class DbContext : Microsoft.EntityFrameworkCore.DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
optionsBuilder.UseSqlServer("Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=YourDatabase");
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);

modelBuilder.Entity(u =>
{
u.HasMany(p => p.Properties).WithOne(p => p.User).HasForeignKey(p => p.UserId);
});

modelBuilder.Entity(u =>
{
u.HasOne(p => p.User).WithMany().HasForeignKey(p => p.UserId);
});

modelBuilder.Entity(u =>
{
u.HasNoKey();
u.HasOne(p => p.User).WithMany().HasForeignKey(p => p.UserId);
});
}
}
```

Imho this should be pretty easy using SQL?

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.