How to map database column to EF model property in a more efficient way than I'm doing now









up vote
1
down vote

favorite












I have a nullable varchar(max) column in SQL Server that I'm mapping to a Guid? in EF code-first. However, this property is actually in a base class that many other entities derive from.



protected override void OnModelCreating(ModelBuilder modelBuilder)

modelBuilder.Entity<Model1>().Property(e => e.Property1).HasConversion(p => p.ToString(), p => (Guid?)Guid.Parse(p));



The above line is repeated many times for each table. Is there a way to tell EF that this is a base class property so the mapping can be declared only once?










share|improve this question



























    up vote
    1
    down vote

    favorite












    I have a nullable varchar(max) column in SQL Server that I'm mapping to a Guid? in EF code-first. However, this property is actually in a base class that many other entities derive from.



    protected override void OnModelCreating(ModelBuilder modelBuilder)

    modelBuilder.Entity<Model1>().Property(e => e.Property1).HasConversion(p => p.ToString(), p => (Guid?)Guid.Parse(p));



    The above line is repeated many times for each table. Is there a way to tell EF that this is a base class property so the mapping can be declared only once?










    share|improve this question

























      up vote
      1
      down vote

      favorite









      up vote
      1
      down vote

      favorite











      I have a nullable varchar(max) column in SQL Server that I'm mapping to a Guid? in EF code-first. However, this property is actually in a base class that many other entities derive from.



      protected override void OnModelCreating(ModelBuilder modelBuilder)

      modelBuilder.Entity<Model1>().Property(e => e.Property1).HasConversion(p => p.ToString(), p => (Guid?)Guid.Parse(p));



      The above line is repeated many times for each table. Is there a way to tell EF that this is a base class property so the mapping can be declared only once?










      share|improve this question















      I have a nullable varchar(max) column in SQL Server that I'm mapping to a Guid? in EF code-first. However, this property is actually in a base class that many other entities derive from.



      protected override void OnModelCreating(ModelBuilder modelBuilder)

      modelBuilder.Entity<Model1>().Property(e => e.Property1).HasConversion(p => p.ToString(), p => (Guid?)Guid.Parse(p));



      The above line is repeated many times for each table. Is there a way to tell EF that this is a base class property so the mapping can be declared only once?







      c# sql-server entity-framework entity-framework-core ef-core-2.0






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 11 at 10:11









      Ivan Stoev

      97.1k765119




      97.1k765119










      asked Nov 11 at 5:17









      user246392

      1,35482953




      1,35482953






















          3 Answers
          3






          active

          oldest

          votes

















          up vote
          2
          down vote



          accepted










          Sure it is possible. With the lack of custom conventions, it is achieved with the "typical" modelBuilder.Model.GetEntityTypes() loop. Something like this (just change the base class and the property names):



          var entityTypes = modelBuilder.Model.GetEntityTypes()
          .Where(t => t.ClrType.IsSubclassOf(typeof(BaseClass)));

          var valueConverter = new ValueConverter<Guid, string>(
          v => v.ToString(), v => (Guid?)Guid.Parse(v));

          foreach (var entityType in entityTypes)
          entityType.FindProperty(nameof(BaseClass.Property1)).SetValueConverter(valueConverter);


          You may also consider using the EF Core provided out of the box Guid to String converter:



          var valueConverter = new GuidToStringConverter();





          share|improve this answer



























            up vote
            0
            down vote













            Better to make next calculation property:



            [Column("Property1")]
            public string Property1Raw get; set;

            [IgnoreDataMember]
            public Guid? Property1

            get => Guid.TryParse(Property1AsString, out Guid result) ? result : (Guid?)null;
            set => Property1Raw = value?.ToString();






            share|improve this answer



























              up vote
              0
              down vote













              Another way to do is it to have a matching base class IEntityTypeConfiguration:



              internal class EntityConfiguration<T> : IEntityTypeConfiguration<T> where T : Entity

              public virtual void Configure(EntityTypeBuilder<T> builder)

              builder.Property(e => e.Property1).HasConversion(p => p.ToString(), p => (Guid?)Guid.Parse(p));
              // ... Other base-specific config here




              (Assuming here your base class is called Entity - change as needed).



              This works better when you use the pattern of factoring out your entity configurations, so yours might be like this:



              protected override void OnModelCreating(ModelBuilder modelBuilder)

              modelBuilder.ApplyConfiguration(new Model1EntityConfiguration());
              modelBuilder.ApplyConfiguration(new Model2EntityConfiguration());
              // ...



              ...



              internal sealed class Model1EntityConfiguration : EntityConfiguration<Model1>

              public override void Configure(EntityTypeBuilder<Model1> builder)

              base.Configure(builder); // <-- here's the key bit
              // ...; e.g.
              builder.Property(c => c.Name).HasMaxLength(80).IsRequired();







              share|improve this answer




















                Your Answer






                StackExchange.ifUsing("editor", function ()
                StackExchange.using("externalEditor", function ()
                StackExchange.using("snippets", function ()
                StackExchange.snippets.init();
                );
                );
                , "code-snippets");

                StackExchange.ready(function()
                var channelOptions =
                tags: "".split(" "),
                id: "1"
                ;
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function()
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled)
                StackExchange.using("snippets", function()
                createEditor();
                );

                else
                createEditor();

                );

                function createEditor()
                StackExchange.prepareEditor(
                heartbeatType: 'answer',
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader:
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                ,
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                );



                );













                draft saved

                draft discarded


















                StackExchange.ready(
                function ()
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53246043%2fhow-to-map-database-column-to-ef-model-property-in-a-more-efficient-way-than-im%23new-answer', 'question_page');

                );

                Post as a guest















                Required, but never shown

























                3 Answers
                3






                active

                oldest

                votes








                3 Answers
                3






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes








                up vote
                2
                down vote



                accepted










                Sure it is possible. With the lack of custom conventions, it is achieved with the "typical" modelBuilder.Model.GetEntityTypes() loop. Something like this (just change the base class and the property names):



                var entityTypes = modelBuilder.Model.GetEntityTypes()
                .Where(t => t.ClrType.IsSubclassOf(typeof(BaseClass)));

                var valueConverter = new ValueConverter<Guid, string>(
                v => v.ToString(), v => (Guid?)Guid.Parse(v));

                foreach (var entityType in entityTypes)
                entityType.FindProperty(nameof(BaseClass.Property1)).SetValueConverter(valueConverter);


                You may also consider using the EF Core provided out of the box Guid to String converter:



                var valueConverter = new GuidToStringConverter();





                share|improve this answer
























                  up vote
                  2
                  down vote



                  accepted










                  Sure it is possible. With the lack of custom conventions, it is achieved with the "typical" modelBuilder.Model.GetEntityTypes() loop. Something like this (just change the base class and the property names):



                  var entityTypes = modelBuilder.Model.GetEntityTypes()
                  .Where(t => t.ClrType.IsSubclassOf(typeof(BaseClass)));

                  var valueConverter = new ValueConverter<Guid, string>(
                  v => v.ToString(), v => (Guid?)Guid.Parse(v));

                  foreach (var entityType in entityTypes)
                  entityType.FindProperty(nameof(BaseClass.Property1)).SetValueConverter(valueConverter);


                  You may also consider using the EF Core provided out of the box Guid to String converter:



                  var valueConverter = new GuidToStringConverter();





                  share|improve this answer






















                    up vote
                    2
                    down vote



                    accepted







                    up vote
                    2
                    down vote



                    accepted






                    Sure it is possible. With the lack of custom conventions, it is achieved with the "typical" modelBuilder.Model.GetEntityTypes() loop. Something like this (just change the base class and the property names):



                    var entityTypes = modelBuilder.Model.GetEntityTypes()
                    .Where(t => t.ClrType.IsSubclassOf(typeof(BaseClass)));

                    var valueConverter = new ValueConverter<Guid, string>(
                    v => v.ToString(), v => (Guid?)Guid.Parse(v));

                    foreach (var entityType in entityTypes)
                    entityType.FindProperty(nameof(BaseClass.Property1)).SetValueConverter(valueConverter);


                    You may also consider using the EF Core provided out of the box Guid to String converter:



                    var valueConverter = new GuidToStringConverter();





                    share|improve this answer












                    Sure it is possible. With the lack of custom conventions, it is achieved with the "typical" modelBuilder.Model.GetEntityTypes() loop. Something like this (just change the base class and the property names):



                    var entityTypes = modelBuilder.Model.GetEntityTypes()
                    .Where(t => t.ClrType.IsSubclassOf(typeof(BaseClass)));

                    var valueConverter = new ValueConverter<Guid, string>(
                    v => v.ToString(), v => (Guid?)Guid.Parse(v));

                    foreach (var entityType in entityTypes)
                    entityType.FindProperty(nameof(BaseClass.Property1)).SetValueConverter(valueConverter);


                    You may also consider using the EF Core provided out of the box Guid to String converter:



                    var valueConverter = new GuidToStringConverter();






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 11 at 10:09









                    Ivan Stoev

                    97.1k765119




                    97.1k765119






















                        up vote
                        0
                        down vote













                        Better to make next calculation property:



                        [Column("Property1")]
                        public string Property1Raw get; set;

                        [IgnoreDataMember]
                        public Guid? Property1

                        get => Guid.TryParse(Property1AsString, out Guid result) ? result : (Guid?)null;
                        set => Property1Raw = value?.ToString();






                        share|improve this answer
























                          up vote
                          0
                          down vote













                          Better to make next calculation property:



                          [Column("Property1")]
                          public string Property1Raw get; set;

                          [IgnoreDataMember]
                          public Guid? Property1

                          get => Guid.TryParse(Property1AsString, out Guid result) ? result : (Guid?)null;
                          set => Property1Raw = value?.ToString();






                          share|improve this answer






















                            up vote
                            0
                            down vote










                            up vote
                            0
                            down vote









                            Better to make next calculation property:



                            [Column("Property1")]
                            public string Property1Raw get; set;

                            [IgnoreDataMember]
                            public Guid? Property1

                            get => Guid.TryParse(Property1AsString, out Guid result) ? result : (Guid?)null;
                            set => Property1Raw = value?.ToString();






                            share|improve this answer












                            Better to make next calculation property:



                            [Column("Property1")]
                            public string Property1Raw get; set;

                            [IgnoreDataMember]
                            public Guid? Property1

                            get => Guid.TryParse(Property1AsString, out Guid result) ? result : (Guid?)null;
                            set => Property1Raw = value?.ToString();







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 11 at 10:27









                            Sergey Shulik

                            678824




                            678824




















                                up vote
                                0
                                down vote













                                Another way to do is it to have a matching base class IEntityTypeConfiguration:



                                internal class EntityConfiguration<T> : IEntityTypeConfiguration<T> where T : Entity

                                public virtual void Configure(EntityTypeBuilder<T> builder)

                                builder.Property(e => e.Property1).HasConversion(p => p.ToString(), p => (Guid?)Guid.Parse(p));
                                // ... Other base-specific config here




                                (Assuming here your base class is called Entity - change as needed).



                                This works better when you use the pattern of factoring out your entity configurations, so yours might be like this:



                                protected override void OnModelCreating(ModelBuilder modelBuilder)

                                modelBuilder.ApplyConfiguration(new Model1EntityConfiguration());
                                modelBuilder.ApplyConfiguration(new Model2EntityConfiguration());
                                // ...



                                ...



                                internal sealed class Model1EntityConfiguration : EntityConfiguration<Model1>

                                public override void Configure(EntityTypeBuilder<Model1> builder)

                                base.Configure(builder); // <-- here's the key bit
                                // ...; e.g.
                                builder.Property(c => c.Name).HasMaxLength(80).IsRequired();







                                share|improve this answer
























                                  up vote
                                  0
                                  down vote













                                  Another way to do is it to have a matching base class IEntityTypeConfiguration:



                                  internal class EntityConfiguration<T> : IEntityTypeConfiguration<T> where T : Entity

                                  public virtual void Configure(EntityTypeBuilder<T> builder)

                                  builder.Property(e => e.Property1).HasConversion(p => p.ToString(), p => (Guid?)Guid.Parse(p));
                                  // ... Other base-specific config here




                                  (Assuming here your base class is called Entity - change as needed).



                                  This works better when you use the pattern of factoring out your entity configurations, so yours might be like this:



                                  protected override void OnModelCreating(ModelBuilder modelBuilder)

                                  modelBuilder.ApplyConfiguration(new Model1EntityConfiguration());
                                  modelBuilder.ApplyConfiguration(new Model2EntityConfiguration());
                                  // ...



                                  ...



                                  internal sealed class Model1EntityConfiguration : EntityConfiguration<Model1>

                                  public override void Configure(EntityTypeBuilder<Model1> builder)

                                  base.Configure(builder); // <-- here's the key bit
                                  // ...; e.g.
                                  builder.Property(c => c.Name).HasMaxLength(80).IsRequired();







                                  share|improve this answer






















                                    up vote
                                    0
                                    down vote










                                    up vote
                                    0
                                    down vote









                                    Another way to do is it to have a matching base class IEntityTypeConfiguration:



                                    internal class EntityConfiguration<T> : IEntityTypeConfiguration<T> where T : Entity

                                    public virtual void Configure(EntityTypeBuilder<T> builder)

                                    builder.Property(e => e.Property1).HasConversion(p => p.ToString(), p => (Guid?)Guid.Parse(p));
                                    // ... Other base-specific config here




                                    (Assuming here your base class is called Entity - change as needed).



                                    This works better when you use the pattern of factoring out your entity configurations, so yours might be like this:



                                    protected override void OnModelCreating(ModelBuilder modelBuilder)

                                    modelBuilder.ApplyConfiguration(new Model1EntityConfiguration());
                                    modelBuilder.ApplyConfiguration(new Model2EntityConfiguration());
                                    // ...



                                    ...



                                    internal sealed class Model1EntityConfiguration : EntityConfiguration<Model1>

                                    public override void Configure(EntityTypeBuilder<Model1> builder)

                                    base.Configure(builder); // <-- here's the key bit
                                    // ...; e.g.
                                    builder.Property(c => c.Name).HasMaxLength(80).IsRequired();







                                    share|improve this answer












                                    Another way to do is it to have a matching base class IEntityTypeConfiguration:



                                    internal class EntityConfiguration<T> : IEntityTypeConfiguration<T> where T : Entity

                                    public virtual void Configure(EntityTypeBuilder<T> builder)

                                    builder.Property(e => e.Property1).HasConversion(p => p.ToString(), p => (Guid?)Guid.Parse(p));
                                    // ... Other base-specific config here




                                    (Assuming here your base class is called Entity - change as needed).



                                    This works better when you use the pattern of factoring out your entity configurations, so yours might be like this:



                                    protected override void OnModelCreating(ModelBuilder modelBuilder)

                                    modelBuilder.ApplyConfiguration(new Model1EntityConfiguration());
                                    modelBuilder.ApplyConfiguration(new Model2EntityConfiguration());
                                    // ...



                                    ...



                                    internal sealed class Model1EntityConfiguration : EntityConfiguration<Model1>

                                    public override void Configure(EntityTypeBuilder<Model1> builder)

                                    base.Configure(builder); // <-- here's the key bit
                                    // ...; e.g.
                                    builder.Property(c => c.Name).HasMaxLength(80).IsRequired();








                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Nov 11 at 10:32









                                    sellotape

                                    5,50221619




                                    5,50221619



























                                        draft saved

                                        draft discarded
















































                                        Thanks for contributing an answer to Stack Overflow!


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid


                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.

                                        To learn more, see our tips on writing great answers.





                                        Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                        Please pay close attention to the following guidance:


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid


                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.

                                        To learn more, see our tips on writing great answers.




                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function ()
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53246043%2fhow-to-map-database-column-to-ef-model-property-in-a-more-efficient-way-than-im%23new-answer', 'question_page');

                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        這個網誌中的熱門文章

                                        What does pagestruct do in Eviews?

                                        Dutch intervention in Lombok and Karangasem

                                        Channel Islands