Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
}
like image 545
silent_coder Avatar asked Oct 18 '22 08:10

silent_coder


1 Answers

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.

like image 141
Tobias Avatar answered Oct 21 '22 05:10

Tobias