Entity Framework Core: Private or Secure Navigation Properties

Is it possible to define navigation properties in EFCore with a closed or secure access level to make this kind of code:

class Model { public int Id { get; set; } virtual protected ICollection<ChildModel> childs { get; set; } } 
+5
source share
2 answers

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

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

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

Update: safe version with refactoring

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

Or use the support box.

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

Alternatively try using the property

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

Remember that with EF Core 1.1 there is a catch: the metadata change should be the last, after all other .HasOne/.HasMany , otherwise it will override the metadata. See Restoring Relationships may result in loss of annotations .

+5
source

I'm not sure if this is possible, the whole model should be accessible and affordable at a low level with any restrictions on DTO ViewModels, etc.

0
source

Source: https://habr.com/ru/post/1268398/


All Articles