Skip to content

Flexible mapping to CLR types and members (Custom O/C Mapping) #240

Open

Description

@rowanmiller

This is a grouping of related issues. Feel free to vote (👍) for this issue to indicate that this is an area that you think we should spend time on, but consider also voting for individual issues for things you consider especially important.


This an "epic" issue for the theme of improvements to mapping of different CLR constructs to standard database concepts. Specific pieces of work will be tracked by linked issues.

Done in 7.0

Done in 8.0

Done in 9.0

Backlog


Although we have had support for POCOs through a few major versions, using EF for persistence still places some undesired constraints on the design choices developers can make on their domain objects.

For example, EF Core still requires that mapped CLR types can be instantiated through constructors without parameters (this is only true for navigation properties now), that they contain both property getters and setters for each mapped scalar and reference property, and that all mapped collection navigation properties are exposed as properties that are of a type that implements ICollection<T>.

Note that POCO proxy functionality introduces additional constraints, e.g. lazy loading requires that property getters are virtual and change tracking proxies (not yet supported in EF Core) require that all properties are virtual at the same time that properties mapped to collections are effectively declared as ICollection<T>.

EF Core also requires each entity type in the model to be mapped to a distinct CLR type, which makes some dynamic model scenarios (#2282) harder.

Moreover, scalar properties on objects have to be of a small set of recognized types in order to be mapped (in EF Core the set of types supported nativly by the provider).

Richer constructs such as collections of scalars or collections of complex types, ordered collections, inheritance in complex types, collection manipulation methods, factory methods, and immutable objects are not supported.

This issue tracks the removal of those constrains as a whole and serves as a parent issue for some individual features that we will track independently:

An old hope

One of many interesting design strategies of EF as an O/RMs was that every EF model defined an abstract data model that is separate from the object model. When using EF in regular O/RM scenarios there are in fact three layered models involved: the storage/database model (often referred to as the S-space model), the conceptual/abstract data model (often referred to as the C-space) and the actual object model (also known as the O-space model). EF also makes use of two mapping specifications: the translation of data access operations between the C-space model and the S-space model is the most well-known and where most of the mapping capabilities of EF focus. The mapping between the C-space and the O-space model is less widely known and in fact since only trivial 1:1 mappings are supported.

There are many historical motivations for this underlying design, including the desire to provide a complete “weakly typed“ programming interface (often referred to as a “value layer”) that could be used in scenarios outside the traditional O/RM space, such as runtime metadata driven user interfaces and tools, database reporting, etc. EntityClient was intended to be such weakly typed API, but it had considerable restrictions (e.g. it was read-only) and some usability issues (e.g. it was designed after an ADO.NET provider without a public DbDataAdapter and with a quite complicated connection string format) on the first version of EF. Since its popularity never took off, the investments necessary to unleash the “value layer” were never completed. In the meanwhile, EF role in solving the traditional O/RM scenario of mapping strongly typed objects to database tables and functions became more and more relevant since EF4, so the lion share of the investments have gone into making EF easier to use in those scenarios, which in many cases meant burying the separation between the abstract data model and the object model even deeper under layers of new API.

In practice the object model can be considered for most intents and purposes a straight realization of what is in C-space. The most commonly used APIs on EF take advantage of this similarity and just conflates C-space and O-space seamlessly, abstracting away the fact that there is a layer of indirection. In other words, although this differentiation between C-space and O-space is real and very explicit in the implementation, it is purposely not evident in most of the EF APIs and usage patterns. A clear example of this is Code First. To a great degree, the usability of the Code First API relies on users being able to ignore the existence of an abstract data model.

While sharing the same meta-model for conceptual models has made it easier to expose EF models through things like OData services, the majority of EF users has never needed to know that there is a difference between the conceptual and object models of their applications.

Regardless of the past motivations for creating this extra layer of indirection, there is potential in the decoupling of the conceptual level (at which most of EF’s mapping, query and update pipeline operates) and the objects level. The basic idea is that by breaking the current status quo of 1:1 O-C mapping, it should be possible to extend EF to support much richer object mapping without having to touch at all the guts of the system.

Activity

  1. added this to the 1.0.0 milestone on May 22, 2014
  2. rowanmiller commented on Nov 10, 2014

    @rowanmiller
    ContributorAuthor

    Here is a good example of this feature (good case to verify against once we implement it) - #1009

  3. modified the milestones: Backlog, 7.0.0 on Dec 1, 2014
  4. divega commented on Sep 1, 2015

    @divega
    Contributor

    @rowanmiller Looking at this it seems that the bug I filed yesterday is more specific about property access while this is the all-encompassing flexible mapping. Would you mind if I just add #2968 as a child, similar to how #857 is a child specific to collection patterns?

  5. rowanmiller commented on Sep 1, 2015

    @rowanmiller
    ContributorAuthor

    @divega yep that works

  6. divega commented on Sep 1, 2015

    @divega
    Contributor

    Otherwise I can merge it all here...

  7. changed the title [-]Flexible mapping to CLR types/properties/methods/etc. (O/C Mapping)[/-] [+]Flexible object mapping to CLR types and members (Custom O/C Mapping)[/+] on Sep 1, 2015
  8. divega commented on Sep 1, 2015

    @divega
    Contributor

    Made some edits to the original text of the issue to add background and additional links to related issues.

  9. changed the title [-]Flexible object mapping to CLR types and members (Custom O/C Mapping)[/-] [+]Flexible mapping to CLR types and members (Custom O/C Mapping)[/+] on Sep 1, 2015
  10. biqas commented on Mar 8, 2016

    @biqas

    Hi,
    the following example is for Illustration how maybe interface definition could be used to map EF structures.

    public class BloggingContext : DbContext
    {
        // Type mapping for materialization
        public DbSet<IBlog, Blog> Blogs { get; set; }
    
        // Materialization can create type on the fly because no specific type was given. (Generators or emitting)
        public DbSet<IPost> Posts { get; set; }
    
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<IBlog>()
                .Property(b => b.Url);
    
            // Optional: provide type creation factory.
            modelBuilder.Entity<IBlog>(() => new Blog());
    
            // Optional: provide collection behavior if non is provided then use default or emitt or generate.
            modelBuilder.Collection<IList<Any>>((IList<Any> collection, Any item) => collection.Add(item));
        }
    }
    
    // Any represents all kind of types which can be used in a collection.
    class Any { }
    
    public class DbSet<T, TEntity> where TEntity : class, T { }
    
    public interface IBlog
    {
        int BlogId { get; set; }
    
        string Url { get; set; }
    
        IList<IPost> Posts { get; set; }
    }
    
    public class Blog : IBlog
    {
        public int BlogId { get; set; }
    
        public string Url { get; set; }
    
        public IList<IPost> Posts { get; set; }
    }
    
    public interface IPost
    {
        int PostId { get; set; }
    
        string Title { get; set; }
    
        string Content { get; set; }
    
        int BlogId { get; set; }
    
        IBlog Blog { get; set; }
    }
    
    public class Post : IPost
    {
        public int PostId { get; set; }
    
        public string Title { get; set; }
    
        public string Content { get; set; }
    
        public int BlogId { get; set; }
    
        public IBlog Blog { get; set; }
    }

    I know there are lot of other scenarios, so if someone has specific questions how for example x,y and z would fit in this kind of mapping, please ask, I will try to provide examples and explanations.

  11. bjorn-ali-goransson commented on Jul 30, 2016

    @bjorn-ali-goransson

    Actually, todays code base is quite close to being able to handle this. It just needs to be 'laxed in some parts. I mean the IClrPropertyGetter/IClrPropertySetter infrastructure is already there.

    I got stuck at the type check in EntityType.AddProperty, I dunno if it would have worked otherwise (probably not...)

    We need to be able to specify, when adding a Property:

    1. Clr type (not needed in practice as PropertyInfo.SetValue takes object)
    2. Resulting primitive backing type (for DB provider)
    3. Getter Serializer (converts from Clr type to Resulting primitive type)
    4. Setter Parser (converts from Resulting primitive type to Clr type)

    And the type check mentioned above needs to not happen if(Flexible).

    Here's a (hopefully somewhat) functioning example of what I'd like to achieve:

    public class Context : DbContext
    {
        private static readonly IServiceProvider _serviceProvider = new ServiceCollection()
            .AddEntityFrameworkSqlServer()
            .AddSingleton<ICoreConventionSetBuilder, MyCoreConventionSetBuilder>()
            .BuildServiceProvider();
    
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder
                .UseInternalServiceProvider(_serviceProvider)
                .UseSqlServer(@"Data Source=.\SQLEXPRESS2014;Initial Catalog=EfCoreTest;Integrated Security=True;");
        }
    
        private class MyCoreConventionSetBuilder : CoreConventionSetBuilder
        {
            public override ConventionSet CreateConventionSet()
            {
                var value = base.CreateConventionSet();
                value.EntityTypeAddedConventions.Add(new MyPropertyDiscoveryConvention());
                return value;
            }
        }
    
        private class MyPropertyDiscoveryConvention : IEntityTypeConvention
        {
            public InternalEntityTypeBuilder Apply(InternalEntityTypeBuilder entityTypeBuilder)
            {
                entityTypeBuilder.Metadata.AddProperty(
                    "Ancestors",
                    propertyType: typeof(string),
                    flexible: true,
                    serialize: JsonConvert.Serialize,
                    parse: value => JsonConvert.Parse<List<int>>((string)value)
                );
    
                return entityTypeBuilder;
            }
        }
    
        public DbSet<Page> Pages { get; set; }
    
        public class Page
        {
            public int Id { get; set; }
            public List<int> Ancestors { get; set; }
        }
    }
    
  12. bjorn-ali-goransson commented on Aug 5, 2016

    @bjorn-ali-goransson

    @rowanmiller any thoughts or progress on this? I really think that just relaxing the checks a bit on this (and maybe generalizing the structure of Property a little) would get us 80% there.

    ( @divega )

    Also, FWIW, I now think that we would be better off with a new AddFlexibleProperty method rather than further overloading the AddProperty.

  13. ma3yta commented on Sep 29, 2016

    @ma3yta

    @rowanmiller what is blocking to implement this. Maybe, I can help with this?

  14. 33 remaining items

  15. smitpatel commented on Sep 3, 2019

    @smitpatel
    Contributor

    @ajcvickers - What exactly needs-cleanup label is?

  16. modified the milestones: Backlog, on Oct 11, 2020
  17. voroninp commented on Oct 14, 2020

    @voroninp

    Proposed for 6.0

    Does it mean not earlier than November 2021?

  18. roji commented on Oct 15, 2020

    @roji
    Member

    @voroninp yes, 6.0 would mean November 2021. Previews would make this available much earlier, though.

  19. atrauzzi commented on Oct 31, 2020

    @atrauzzi

    I'm just here to say I've been waiting 6 years and counting for polymorphic relations using discriminators. I think it's more than made a case for itself from the digging I've been doing here.


    Something along the lines of:

    Integration
    IIntegratable
    User : IIIntegratable
    Organization : IIntegratable

    Therefore, the table integration in the database gets a integratable_type and integratable_id column, then I could go:

    integration.Integratable...; // (returns a IIntegratable that can be passed through pattern matching to detect concrete type)
    // and of course:
    user.Integrations...; // (returns a list of `Integration` instances)

  20. added
    composite-issue
    on Dec 6, 2022
  21. modified the milestones: , Backlog on Dec 7, 2022
  22. added theissue type on Jun 15, 2025
  23. changed the issue type fromtoon Oct 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-o/c-mappingcomposite-issue

    Type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions