4

我有两个具有一对多关联的实体类 Project 和 Product:

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

为了映射受保护的属性,我使用了这个解决方案

但是我遇到了以下问题:

1)如果我配置项目和产品之间的一对多关联

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

然后 Project.GetProducts() 失败,似乎延迟加载不起作用。但如果我改为

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

然后一切正常。

2)如果我将属性“Project.Products”从 protected 更改为public,那么上述两种方式都可以。

在这种情况下有什么问题?

4

2 回答 2

0

删除GetProducts并执行以下操作:

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

注意protectedsetter 上的关键字。我刚试过这个,对我来说效果很好。

于 2013-03-17T15:56:24.467 回答
0

属性必须是公开的才能让代理工作。看这里

于 2013-03-17T15:25:44.263 回答