Entity Framework Core: private or protected navigation properties

為{幸葍}努か 提交于 2019-12-22 04:07:07

问题


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; }  
}

回答1:


You have two options, using type/string inside the model builder.

modelBuilder.Entity<Model>(c =>
    c.HasMany(typeof(Model), "childs")
        .WithOne("parent")
        .HasForeignKey("elementID");
);

Not 100% sure it works with private properties, but it should.

Update: Refactoring-safe version

modelBuilder.Entity<Model>(c =>
    c.HasMany(typeof(Model), nameof(Model.childs)
        .WithOne(nameof(Child.parent))
        .HasForeignKey("id");
);

Or use a backing field.

var elementMetadata = Entity<Model>().Metadata.FindNavigation(nameof(Model.childs));
    elementMetadata.SetField("_childs");
    elementMetadata.SetPropertyAccessMode(PropertyAccessMode.Field);

Alternatively try that with a property

var elementMetadata = Entity<Model>().Metadata.FindNavigation(nameof(Model.childs));
    elementMetadata.SetPropertyAccessMode(PropertyAccessMode.Property);

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.




回答2:


I am not sure if that is possible, the whole model should be available and accessible at a low level with any restrictions on DTO's ViewModels etc



来源:https://stackoverflow.com/questions/44285198/entity-framework-core-private-or-protected-navigation-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!