Entity Framework Core:私有或受保护的导航属性 [英] Entity Framework Core: private or protected navigation properties
问题描述
是否可以以某种方式在 EFCore 中定义具有私有或受保护访问级别的导航属性以使此类代码工作:
Is it somehow possible to define navigation properties in EFCore with private or protected access level to make this kind of code work:
class Model {
public int Id { get; set; }
virtual protected ICollection<ChildModel> childs { get; set; }
}
推荐答案
您有两个选择,在模型构建器中使用类型/字符串.
You have two options, using type/string inside the model builder.
modelBuilder.Entity<Model>(c =>
c.HasMany(typeof(Model), "childs")
.WithOne("parent")
.HasForeignKey("elementID");
);
不能 100% 确定它适用于私有财产,但应该可以.
Not 100% sure it works with private properties, but it should.
modelBuilder.Entity<Model>(c =>
c.HasMany(typeof(Model), nameof(Model.childs)
.WithOne(nameof(Child.parent))
.HasForeignKey("id");
);
或者使用支持字段.
var elementMetadata = Entity<Model>().Metadata.FindNavigation(nameof(Model.childs));
elementMetadata.SetField("_childs");
elementMetadata.SetPropertyAccessMode(PropertyAccessMode.Field);
或者尝试使用属性
var elementMetadata = Entity<Model>().Metadata.FindNavigation(nameof(Model.childs));
elementMetadata.SetPropertyAccessMode(PropertyAccessMode.Property);
请注意,从 EF Core 1.1 开始,有一个问题:在所有其他 .HasOne/.HasMany
配置之后,必须最后完成元数据修改,否则会覆盖元数据.请参阅重新建立关系可能导致注释丢失.
Be aware, as of EF Core 1.1, there is a catch: The metadata modification must be done last, after all other .HasOne/.HasMany
configuration, otherwise it will override the metadata. See Re-building relationships can cause annotations to be lost.
这篇关于Entity Framework Core:私有或受保护的导航属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!