Proxy 实体框架:POCO的自定义代理

Proxy 实体框架:POCO的自定义代理,proxy,lazy-loading,entity-framework-6,Proxy,Lazy Loading,Entity Framework 6,我正在使用EF6,我非常喜欢动态代理,它支持延迟加载和更改跟踪。无论如何,我不高兴的是,在访问属性而不是加载数据时,首先调用枚举数或count属性时,会触发延迟加载。因此,我尝试禁用代理并用自定义代理替换它们。使用自定义对象上下文并重载CreateObject方法很容易。不幸的是,ObjectMaterialized事件无法替换实体,我也无法替换查询中的实体。对象的创建深入到框架的内部类中 有人知道如何使用自定义代理吗?或者如何替换对象查询中具体化的实体?您应该。包括要获取的属性,以避免错误 这

我正在使用EF6,我非常喜欢动态代理,它支持延迟加载和更改跟踪。无论如何,我不高兴的是,在访问属性而不是加载数据时,首先调用枚举数或count属性时,会触发延迟加载。因此,我尝试禁用代理并用自定义代理替换它们。使用自定义对象上下文并重载CreateObject方法很容易。不幸的是,ObjectMaterialized事件无法替换实体,我也无法替换查询中的实体。对象的创建深入到框架的内部类中


有人知道如何使用自定义代理吗?或者如何替换对象查询中具体化的实体?

您应该
。包括要获取的属性,以避免错误

这是好的,因为它将执行一个查询:

public class User
{
    public int Id { get; set; }
    public string Name { get; set ;}

    public virtual ICollection<Post> Posts { get; set; }
    public virtual ICollection<Comment> Comments { get; set; }
}

public class Post
{
    public int Id { get; set; }
    public string Title { get; set ; }

    public int AuthorId { get; set; }
    public virtual User Author { get; set; }

    public virtual ICollection<Comment> Comments { get; set; }
}

public class Comment
{
    public int Id { get; set; }
    public string Note { get; set ;}

    public int PostId { get; set; }
    public virtual Post Post { get; set; }

    public int AuthorId { get; set; }
    public virtual User Author { get; set; }
}

public class BlogContext : DbContext
{
    public DbSet<User> Users { get; set; }
    public DbSet<Post> Posts { get; set; }
    public DbSet<Comment> Comments { get; set; }
} 
using (var db = new BlogContext())
{
    var user = db.Users.Single(u => u.Id=5));  // +1 query
    foreach (var post in user.Posts) // N queries
    {
       var message = String.Format("{0} wrote {1}", user.Name, post.Title);
       Console.WriteLine(message);

       foreach (var comment in post.Comments) // N * M queries!
       {
           // and that .Author make N * M MORE!
           var message = String.Format("\t{0} commented {1}", comment.Author.Name, comment.Note);
           Console.WriteLine(message);
       }
    }
}
using (var db = new BlogContext())
{
    var user = db.Users
                 .Single(u => u.Id=5))
                 .Include(u => u.Posts) // eliminates the N post queries
                 .Include(u => u.Posts.Comments) // eliminates the M comment queries
                 .Include(u => u.Posts.Comments.Author); // eliminates the M comment author queries

    foreach (var post in user.Posts) // N queries
    {
       var message = String.Format("{0} wrote {1}", user.Name, post.Title);
       Console.WriteLine(message);

       foreach (var comment in post.Comments) // N * M queries!
       {
           // and that .Author make N * M MORE!
           var message = String.Format("\t{0} commented {1}", comment.Author.Name, comment.Note);
           Console.WriteLine(message);
       }
    }
}