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) {
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?
source share