Problems displaying private property

I have two classes of Project and Product entities with a one-to-many association:

public class Product { public string Id {get; set;} public virtual Project Project {get; set;} } public class Project { public string Id {get; set;} protected virtual List<Product> Products {get; set;} public ReadOnlyCollection<Product> GetProducts() { return Products.AsReadOnly(); } public class PropertyAccessExpressions { public static Expression<Func<Project, ICollection<Product>>> Products = x => x.Products; } } public class MyDbContext: DbContext { public MyDbContext(string connectionString): base(connectionString){} public DbSet<Project> Projects {get; set;} public DbSet<Product> Products {get; set;} protected override void OnModelCreating(DbModelBuilder modelBuilder) { //// project.GetProducts() fails for the following configuratin //modelBuilder.Entity<Product>() // .HasRequired(p => p.Project).WithMany(Project.PropertyAccessExpressions.Products); // The following is OK modelBuilder.Entity<Project>() .HasMany(Project.PropertyAccessExpressions.Products).WithRequired(p => p.Project); } } class Program { static void Main(string[] args) { var context = new MyDbContext(@"data source=localhost;initial catalog=MyTestDb;integrated security=True;"); context.Database.Delete(); context.Database.Create(); var project1 = new Project { Id = "ProjectId1" }; context.Projects.Add(project1); context.Products.Add(new Product { Id = "ProductId1", Project = project1 }); context.Products.Add(new Product { Id = "ProductId2", Project = project1 }); context.SaveChanges(); var project = context.Projects.ToList()[0];; var products = project.GetProducts().ToList(); Debug.Assert(products.Count == 2); } } 

To display a protected property, I use this solution .

But I ran into the following problems:

1) if I set up a one-to-many relationship between Project and Product using

 modelBuilder.Entity<Product>.HasRequied(p => p.Project).WithMany(Project.PropertyAccessExpressions.Products); 

Then Project.GetProducts () fails, and it seems that lazy loading is not working. But if I switch to

 modelBuilder.Entity<Project> .HasMany(Project.PropertyAccessExpressions.Products).WithRequired(p => p.Project); 

Then everything is all right.

2) If I changed the property "Project.Products" from protected to public , then both of the above methods are in order.

What is wrong with this situation?

+4
source share
2 answers

Properties must be publicly available for proxies to work. See here

0
source

Uninstall GetProducts and just do the following:

 public virtual List<Product> Products {get; protected set;} 

Pay attention to the protected keyword in the customizer. I just tried this and it worked well for me.

0
source

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


All Articles