efcore
efcore copied to clipboard
Keyless type with property that looks like collection navigation does not fail model validation
Instead, it is just ignored. Reference navigations will cause validation to fail.
Code:
public class Blog
{
public string? Name { get; set; }
public virtual List<Post> Posts { get; } = new();
}
public class Post
{
public string? Title { get; set; }
}
public class SomeDbContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.UseSqlServer(@"Data Source=(LocalDb)\MSSQLLocalDB;Database=AllTogetherNow")
.LogTo(Console.WriteLine, LogLevel.Information)
.EnableSensitiveDataLogging();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>().HasNoKey();
modelBuilder.Entity<Post>().HasNoKey();
}
}
public class Program
{
public static async Task Main()
{
using (var context = new SomeDbContext())
{
await context.Database.EnsureDeletedAsync();
await context.Database.EnsureCreatedAsync();
await context.SaveChangesAsync();
}
}
}
Model:
Model:
EntityType: Blog Keyless
Properties:
Name (string)
EntityType: Post Keyless
Properties:
Title (string)
This is apparently by design:
- https://github.com/dotnet/efcore/blob/adf3a1309775f655fd4596237c2f7bb58961661e/test/EFCore.Tests/ModelBuilding/OneToManyTestBase.cs#L931
- https://github.com/dotnet/efcore/pull/23195
We should decide if this is also okay for ad-hoc types, which are always keyless.
Note from triage: leave behavior unchanged for normal keyless types, but throw in validation for ad-hoc types.