EntityFramework 核心(七)如何映射protected/private 属性

sil*_*der 5 c# entity-framework entity-framework-core

看起来像映射到 db 的私有/受保护属性的方式在 EntityFramework 核心中发生了变化

那么我应该怎么做才能正确映射这个类:

class Model
{
   protected string _roles {get; set;}
   [NotMapped] 
   public IEnumerables<RoleName> Roles => Parser_rolesToRoleNames(_roles)
}
Run Code Online (Sandbox Code Playgroud)

Tob*_*ias 3

我不明白你的NotMapped-Property,因为它似乎没有名字?

要使 EF Core 映射受保护的属性,请在 OnModelCreating 中的 DbContext 中使用 EntityTypeBuilder.Property-Method:

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

    base.OnModelCreating(modelBuilder);
}
Run Code Online (Sandbox Code Playgroud)

在创建 batabase 期间,会生成相应的列。

要使 EF 将私有属性的值写入数据库,您需要覆盖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();
        }
Run Code Online (Sandbox Code Playgroud)

这样,您的私有属性的所有值都会添加到相应的更改跟踪器条目中,并在插入/更新时写入数据库。