Skip to content

Support single configuration for all uses of an owned type, shared type, or some arbitrary base class/interface #6787

Description

@arruw

Previous non core version of Entity Framework had something like this:

modelBuilder.Type<IEntity>().HasKey(e => e.Id);

I'm curious if this is planned for core version to?

I tried to implement something similar with reflection. https://gist.github.com/matjazmav/2e7335c12c55c4f6692b637bccf651bb There is only one problem with this implementation, casting object to EntityModelBuilder<TEntity> (this is marked with // TODO in the gist snippet). Anyone wan't to help me solve this?

Thanks!

Activity

  1. rowanmiller commented on Oct 17, 2016

    @rowanmiller
    Contributor

    We don't have the equivalent functionality in EF Core yet, but you can write something like this (less pretty, but does the same thing).

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        foreach (var entity in modelBuilder.Model.GetEntityTypes().Where(e => typeof(IEntity).IsAssignableFrom(e.ClrType)))
        {
            modelBuilder.Entity(entity.Name).HasKey(nameof(IEntity.Key));
        }
    }
  2. changed the title [-]Configure base class and/or interface of entity with Fluent API and reflection.[/-] [+]Modeling: Bulk configuration based on unmapped base types[/+] on Oct 24, 2016
  3. added this to the milestone on Oct 24, 2016
  4. changed the title [-]Modeling: Bulk configuration based on unmapped base types[/-] [+]Model Definition: Bulk configuration based on unmapped base types[/+] on Oct 24, 2016
  5. AndriySvyryd commented on Apr 13, 2017

    @AndriySvyryd
    Member

    With this modelBuilder.Owned<>() would be obsolete.

    Related to #3867
    Superseeds #14047

  6. modified the milestones: Backlog, 2.0.0 on Apr 17, 2017
  7. chrispickford commented on Sep 27, 2018

    @chrispickford

    The workaround mentioned above doesn't seem to be working for inherited property definitions. I have the following statement in my OnModelCreating():

    foreach (var entity in modelBuilder.Model.GetEntityTypes()
      .Where(e => typeof(IEntity).IsAssignableFrom(e.ClrType)))
    {
      modelBuilder.Entity(entity.Name).Property(nameof(IEntity.Uuid))
        .IsRequired().HasDefaultValueSql("NEWID()");
    }
    

    I'd expect this produce the following line in the migration for each IEntity, but it does not:

    Uuid = table.Column<Guid>(nullable: false, defaultValueSql: "NEWID()")
    
  8. ajcvickers commented on Sep 27, 2018

    @ajcvickers
    Contributor

    @chrispickford It works for me in a simple test:

    public interface IEntity
    {
        Guid Id { get; set; }
    }
    
    public class Vehicle : IEntity
    {
        public Guid Id { get; set; }
        public string VehicleIdentificationNumber { get; set; }
    }
    
    public class VehiclePrototype : IEntity
    {
        public Guid Id { get; set; }
        public DateTimeOffset? PressReleaseAt { get; set; }
    }
    
    public class BloggingContext : DbContext
    {
        private static readonly LoggerFactory Logger
            = new LoggerFactory(new[] { new ConsoleLoggerProvider((_, __) => true, true) });
    
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            => optionsBuilder
                .UseLoggerFactory(Logger)
                .UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Test;ConnectRetryCount=0");
    
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Vehicle>();
            modelBuilder.Entity<VehiclePrototype>();
    
            foreach (var entity in modelBuilder.Model.GetEntityTypes()
                .Where(e => typeof(IEntity).IsAssignableFrom(e.ClrType)))
            {
                modelBuilder.Entity(entity.Name).Property(nameof(IEntity.Id))
                    .IsRequired().HasDefaultValueSql("NEWID()");
            }
        }
    }
    
    public class Program
    {
        public static async Task Main()
        {
            using (var context = new BloggingContext())
            {
                await context.Database.EnsureDeletedAsync();
                await context.Database.EnsureCreatedAsync();
    
                context.Add(new Vehicle());
                context.Add(new VehiclePrototype());
                context.SaveChanges();
            }
        }
    }
  9. chrispickford commented on Oct 1, 2018

    @chrispickford

    @ajcvickers Apologies, in my haste I constructed an incorrect example. The IEntity should be an abstract class, e.g:

    public abstract class Entity
    {
      public int Id { get; set; }
      public byte[] RowVersion { get; set; }
      public Guid Uuid { get; set; }
    }
    
  10. 6 remaining items

  11. visschersm commented on Jan 12, 2021

    @visschersm

    Previous non core version of Entity Framework had something like this:

    modelBuilder.Type<IEntity>().HasKey(e => e.Id);

    I'm curious if this is planned for core version to?

    I tried to implement something similar with reflection. https://gist.github.com/matjazmav/2e7335c12c55c4f6692b637bccf651bb There is only one problem with this implementation, casting object to EntityModelBuilder<TEntity> (this is marked with // TODO in the gist snippet). Anyone wan't to help me solve this?

    Thanks!

    Would really love to see this, are there any current plans to implement this a future version of EFCore?
    Or are there new ways in EFCore 5 that I can use to get to the same result?

    Currently using reflection to configure my interface derived entities, but like the Framework interface configuration way more.

  12. ajcvickers commented on Jan 12, 2021

    @ajcvickers
    Contributor

    @visschersm This issue is in the Backlog milestone. This means that it is not planned for the next release (EF Core 6.0). We will re-assess the backlog following the this release and consider this item at that time. However, keep in mind that there are many other high priority features with which it will be competing for resources.

  13. AndriySvyryd commented on Aug 20, 2021

    @AndriySvyryd
    Member

    Proposed API design: #12229 (comment)

  14. ajcvickers commented on Oct 27, 2021

    @ajcvickers
    Contributor

    Consider query filters when working on this. See #10257.

  15. added theissue type on Jun 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions