27

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?

Gluip
  • 2,917
  • 4
  • 37
  • 46
  • 1
    I might add that EF supports private setters, so at least you can prevent setting TypeId from outside your class. – Gert Arnold Apr 29 '12 at 15:08

8 Answers8

80

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;
    }
}
crimbo
  • 10,308
  • 8
  • 51
  • 55
  • 2
    Where does this "Column" attribute come from? Is it a custom attribute that you created or is it something coming from EF? – Gimly Apr 15 '14 at 13:27
  • It's a standard attribute used by EF, but not in the EF lib: System.ComponentModel.DataAnnotations.Schema.ColumnAttribute, which is in System.ComponentModel.DataAnnotations.dll. – crimbo Apr 16 '14 at 17:02
  • 3
    Wish I could give you about 10 upvotes. Saved me a bunch of time – Stephen M. Redd Oct 14 '14 at 04:54
  • The sad thing here seems to be that you can not name the public property `TypeId` and have the private property named `_typeId` with the attribute `[Column("TypeId")]` specified. – furier May 11 '15 at 11:29
  • furier - Have you tried that with `[NotMapped]` on the public property? I haven't tried this specifically, but it seems like it should be workable. – crimbo May 11 '15 at 15:35
  • Bonus points for this one: my entity has a ComplexType property (which itself is a concrete implementation of a generic class) containing a private property I would like mapped in this way. (The private property belongs to the generic base class). Any clues on how that could be accomplished? – Matt Jenkins May 13 '16 at 21:20
  • 1
    @MattJenkins: Per (https://msdn.microsoft.com/en-us/library/kyaxdd3x(v=vs.110).aspx), it looks like `BindingFlags.NonPublic` does not include private properties on base classes - it does return protected properties on base classes. If you can't make the base class property protected, you'll need to write a method to walk the base types and return their properties, and substitute that for the `type.GetProperties()` call. I don't think this is generally the right behavior, so I haven't updated my answer. – crimbo May 17 '16 at 20:34
18

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

Community
  • 1
  • 1
Jayantha Lal Sirisena
  • 21,216
  • 11
  • 71
  • 92
  • 19
    Times they are a-changin' - it is possible now, see http://stackoverflow.com/a/13810766/861716 – Gert Arnold Dec 11 '12 at 08:03
  • In addition to @Gert's remark, I have empirically noticed in EF5 that public properties with private setters correctly map with default code first conventions. – Eric J. Oct 16 '13 at 00:15
5

Another workaround might be to set your field as internal:

    [NotMapped]
    public dynamic FacebookMetadata {
        get
        {
            return JObject.Parse(this.FacebookMetadataDb);
        }
        set
        {
            this.FacebookMetadataDb = JsonConvert.SerializeObject(value);
        }
    }

    ///this one
    internal string FacebookMetadataDb { get; set; }

and add it to tour model:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<System.Data.Entity.ModelConfiguration.Conventions.ManyToManyCascadeDeleteConvention>();

        ///here
        modelBuilder.Entity<FacebookPage>().Property(p => p.FacebookMetadataDb);

        base.OnModelCreating(modelBuilder);
    }
Jean F.
  • 1,775
  • 1
  • 19
  • 16
3

If you like Attributes (like me) and you're using EF Core. You could use the following approach.

First, Create an attribute to mark private or properties:

using System;
using System.ComponentModel.DataAnnotations.Schema;
...

[System.AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = false)]
public sealed class ShadowColumnAttribute : ColumnAttribute
{
    public ShadowColumnAttribute() { }
    public ShadowColumnAttribute(string name): base(name) { }
}


public static class ShadowColumnExtensions
{
    public static void RegisterShadowColumns(this ModelBuilder builder)
    {
        foreach (var entity in builder.Model.GetEntityTypes())
        {
            var properties = entity.ClrType
                .GetProperties(BindingFlags.Instance | BindingFlags.NonPublic)
                .Select(x => new { prop = x, attr = x.GetCustomAttribute<ShadowColumnAttribute>() })
                .Where(x => x.attr != null);

            foreach (var property in properties)
                entity.AddProperty(property.prop);
        }
    }
}

Then, mark the properties you would like to stay private.

public class MyEntity
{
    [Key]
    public string Id { get; set; }

    public bool SomeFlag { get; set; }

    public string Name => SomeFlag ? _Name : "SomeOtherName";

    [ShadowColumn(nameof(Name))]
    string _Name { get; set; }
}

Finally, in your DbContext, place this at the end of your OnModelCreating method:

protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);

    // ...
    builder.RegisterShadowColumns();   
}
Prince Owen
  • 1,225
  • 12
  • 20
1

Try this.

  public class UserAccount
    { 
       private string Username { get; set;}
    }



   public class UserAccountConfiguration :IEntityTypeConfiguration<UserAccount>
     {
       public void Configure(EntityTypeBuilder<UserAccount> builder)
         {
           builder.Property(c => c.Username);
         }
}

and then in DbContext

protected override void OnModelCreating(ModelBuilder modelBuilder)
  {
    modelBuilder.ApplyConfiguration(new UserAccount.UserAccountConfiguration());
  }
CatCode91
  • 41
  • 6
0

Extending @crimbo's answer above ( https://stackoverflow.com/a/21686896/3264286 ), here's my change to include public properties with private getters:

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)
                                 .Union(
                                        type.GetProperties(BindingFlags.SetProperty | BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance)
                                            .Where(propInfo => propInfo.GetCustomAttributes(typeof(ColumnAttribute), true).Length > 0
                                                               && propInfo.GetGetMethod().IsNull())
                                  )
                                 .ToArray();
    return matchingProperties.Length == 0 ? null : matchingProperties;
}
Community
  • 1
  • 1
Delorian
  • 330
  • 1
  • 3
  • 13
0

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<int>
    {
        //Has to be a property
        private string _Tags {get; set;}

        [NotMapped]
        public string[] Tags
        {
            get => _Tags == null ? null : JsonConvert.DeserializeObject<string[]>(_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<Report>
        {
            public ReportConfiguration()
            {
                Property(p => p._tags).HasColumnName("Tags");
            }
        }
    }

In your context add the following:

using Models.ReportBuilder;
public partial class ReportBuilderContext:DbContext
{
    public DbSet<Report> 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/

rahicks
  • 573
  • 7
  • 19
0

As seen in your model you grant read access to the property. So maybe you want to block set access and map to EF using a private setter. Like this.

[Required]
private int TypeId { get; private set; }
Jonathan Ramos
  • 1,921
  • 18
  • 21