实体框架核心:私有或受保护的导航属性 [英] Entity Framework Core: private or protected navigation properties

查看:107
本文介绍了实体框架核心:私有或受保护的导航属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在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; }  
}


推荐答案

您有两个选择,

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.

这篇关于实体框架核心:私有或受保护的导航属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆