实体框架,渴望加载实体

时间:2014-11-12 20:59:41

标签: c# asp.net-mvc angularjs linq

我有3个课程,我想在ASP.NET MVC C#WEBAPI应用程序上相互“交谈”。它们是项目,只能有一个用户,但用户可以在多个上生成多个评论 >项目评论可以有多个用户但只有一个

我的课程如下:

public class Item
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }

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

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

    public ICollection<Item> Items { get; set; }
    public ICollection<Comment> Comments { get; set; }
}  

public class Comment
{
    public int Id { get; set; }
    public string Message { get; set; }
    public bool Important { get; set; }

    public Item Item { get; set; }
    public User User { get; set; }
}

我正在使用angularJs前端,所以我没有得到永远重复的循环,我已经配置了以下内容:

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Serialize;
        GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

我正在使用实体框架6,我希望显示所有项,包括评论评论过的用户

我有阅读和感受?使用Linq的投影可能是最好的吗?

我的dbContext中有以下内容。 (P.S,我已禁用LazyLoading,并包含System.Data.Entity命名空间)

using(var _db = new dbContext)
{
   var model = _db.Items.Include(i=>i.Comments.Select(p=>p.User).Select(vm=>new ViewModelItem(){
     //here I think is where I would say.... 
     ViewModelItem.Name = x.Name,
     ViewModelItem.Description = x.Description,
     ViewModelItem.Comments = ///
     ViewModelItem.Comments.User.Name = ///
   })).ToList();

  return Ok(model);
}

我不确定从哪里开始。

所以我想显示所有评论,并包含拥有 用户,但也包含用户 全部该商品的评论以及对该商品发表评论的所有用户

不会造成无限循环。

如果我不清楚,请让我澄清一下。我们非常感谢任何帮助。

谢谢

1 个答案:

答案 0 :(得分:1)

假设你的评论数据很好,那就应该这样做。

    var model = db.Comment.Select(p=>
    new ViewModelItem { 
        Name =   p.User.Name,
        Comments=p,
        Description=p.Item.Description,
    });
相关问题