mapping private property entity framework code first

前端 未结 7 1890
遇见更好的自我
遇见更好的自我 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:28

    Here's a convention you can use in EF 6+ to map selected non-public properties (just add the [Column] attribute to a property).

    In your case, you'd change TypeId to:

        [Column]
        private int TypeId { get; set; }
    

    In your DbContext.OnModelCreating, you'll need to register the convention:

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Add(new NonPublicColumnAttributeConvention());
        }
    

    Finally, here's the convention:

    /// 
    /// Convention to support binding private or protected properties to EF columns.
    /// 
    public sealed class NonPublicColumnAttributeConvention : Convention
    {
    
        public NonPublicColumnAttributeConvention()
        {
            Types().Having(NonPublicProperties)
                   .Configure((config, properties) =>
                              {
                                  foreach (PropertyInfo prop in properties)
                                  {
                                      config.Property(prop);
                                  }
                              });
        }
    
        private IEnumerable NonPublicProperties(Type type)
        {
            var matchingProperties = type.GetProperties(BindingFlags.SetProperty | BindingFlags.GetProperty | BindingFlags.NonPublic | BindingFlags.Instance)
                                         .Where(propInfo => propInfo.GetCustomAttributes(typeof(ColumnAttribute), true).Length > 0)
                                         .ToArray();
            return matchingProperties.Length == 0 ? null : matchingProperties;
        }
    }
    

提交回复
热议问题