InvalidOperationException on collection ThenInclude on keyless entities
- 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
Assessment
This issue has not been assessed yet.