Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mapping private property entity framework code first [duplicate]

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 VenueType Type
    {
        get { return (VenueType) TypeId; }
        set { TypeId = (int) value; }
    }

    private int TypeId { get; set; }

But how can I make this property private and still map it. In other words:

How can I map a private property using EF 4.1 code first?

like image 395
Gluip Avatar asked Oct 01 '11 11:10

Gluip


2 Answers

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:

/// <summary> /// Convention to support binding private or protected properties to EF columns. /// </summary> public sealed class NonPublicColumnAttributeConvention : Convention {      public NonPublicColumnAttributeConvention()     {         Types().Having(NonPublicProperties)                .Configure((config, properties) =>                           {                               foreach (PropertyInfo prop in properties)                               {                                   config.Property(prop);                               }                           });     }      private IEnumerable<PropertyInfo> 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;     } } 
like image 144
crimbo Avatar answered Sep 20 '22 03:09

crimbo


you can't map private properties in EF code first. You can try it changing it in to protected and configuring it in a class inherited from EntityConfiguration .
Edit
Now it is changed , See this https://stackoverflow.com/a/13810766/861716

like image 26
Jayantha Lal Sirisena Avatar answered Sep 19 '22 03:09

Jayantha Lal Sirisena