efcore icon indicating copy to clipboard operation
efcore copied to clipboard

Keyless type with property that looks like collection navigation does not fail model validation

Open ajcvickers opened this issue 2 years ago • 2 comments

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)

ajcvickers avatar Jan 13 '23 13:01 ajcvickers

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.

ajcvickers avatar Jan 13 '23 16:01 ajcvickers

Note from triage: leave behavior unchanged for normal keyless types, but throw in validation for ad-hoc types.

ajcvickers avatar Jan 19 '23 15:01 ajcvickers