mapping private property entity framework code first

前端 未结 7 1913
遇见更好的自我
遇见更好的自我 2020-11-27 17:23

I am using EF 4.1 and was look for a nice workaround for the lack of enum support. A backing property of int seems logical.

    [Required]
    public VenueT         


        
7条回答
  •  日久生厌
    2020-11-27 17:34

    Another way to handle this is to defines a custom entity configuration and add a binding for that.

    In your class add a class that inherits from EntityTypeConfiguration (This can be found in System.Data.Entity.ModelConfiguration)

    public partial class Report : Entity
        {
            //Has to be a property
            private string _Tags {get; set;}
    
            [NotMapped]
            public string[] Tags
            {
                get => _Tags == null ? null : JsonConvert.DeserializeObject(_Tags);
                set => _Tags = JsonConvert.SerializeObject(value);
            }
    
            [MaxLength(100)]
            public string Name { get; set; }
    
            [MaxLength(250)]
            public string Summary { get; set; }
    
            public string JsonData { get; set; }
    
            public class ReportConfiguration: EntityTypeConfiguration
            {
                public ReportConfiguration()
                {
                    Property(p => p._tags).HasColumnName("Tags");
                }
            }
        }
    

    In your context add the following:

    using Models.ReportBuilder;
    public partial class ReportBuilderContext:DbContext
    {
        public DbSet Reports { get; set; }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new Report.ReportConfiguration());
            base.OnModelCreating(modelBuilder);
        }
    }
    

    Wish I could say I found this on my own, but I stumbled upon it here:https://romiller.com/2012/10/01/mapping-to-private-properties-with-code-first/

提交回复
热议问题