EntityFramework core (7th) how to map protected/private properties

c# entity-framework entity-framework-core

Question

Looks like the way how private/protected properties mapped to db was changed in EntityFramework core

So what should I do to be able correctly map this class:

class Model
{
   protected string _roles {get; set;}
   [NotMapped] 
   public IEnumerables<RoleName> Roles => Parser_rolesToRoleNames(_roles)
}
1
2
5/26/2017 12:59:34 PM

Popular Answer

I do not understand your NotMapped-Property, because it seems to have no name?

To make EF Core map your protected property anyway, in your DbContext in OnModelCreating use the EntityTypeBuilder.Property-Method:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Model>()
        .Ignore(m => m.NotMappedProperty)
        .Property(typeof(string), "_roles");

    base.OnModelCreating(modelBuilder);
}

During batabase creation, the respective column is generated.

To make EF write the values of the private properies to the database, you need to override SaveChanges:

 public override int SaveChanges()
        {
            foreach (var entry in ChangeTracker.Entries())
            {
                foreach (var pi in entry.Entity.GetType().GetProperties(BindingFlags.Instance | BindingFlags.NonPublic))
                {
                    entry.Property(pi.Name).CurrentValue = pi.GetValue(entry.Entity);
                }
            }
            return base.SaveChanges();
        }

This way all values of your private properties are added to the corresponding change tracker entries and are written to the database on Insert / Update.

2
6/14/2016 12:03:20 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow