Reputation: 6502
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)
}
Upvotes: 6
Views: 4391
Reputation: 31
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.
Upvotes: 3