繁体   English   中英

如何将 LINQ 中的表与 aspnetusers 连接,然后使用 ViewModel 的结果创建新的 object

[英]How to join table in LINQ with aspnetusers and then create new object with results for ViewModel

只是想知道我应该在select 新块中添加什么来检索 SQL 查询结果。 我有一个 BlogViewModel,以及两个表 blog 和 users。 我想加入这两个表得到结果,然后在 object 中有这个我可以传递给 View。

        public IActionResult Index()
        {
            
           
            List<BlogViewModel> blogs = _db.blog.ToList();  //add elements into blogs list   
            List<IdentityUserHelper> users = _db.Users.ToList(); //add elements into users

            var result = from b in blogs   //"blogs" is list
                         join u in users   //"users" is list
                         on b.userID equals u.Id into group1 //join tables blogs with aspnetusers
            select new    //below is object initliazer
            {
            //I want to join table with aspnetusers?? don't know what to put in here

                
            };

            var blogList = new List<BlogViewModel>();  //create list for blogs
            
            foreach (var test in result) //iterate through queryresult
            {
                blogList.Add(new BlogViewModel
                {
                    blogID = test.blogID,
                    blogContent = test.blogContent
                    userID = test.userID

                }
                );
    public class BlogViewModel
    {
        [Key]
        public int blogID { get; set; }

        public string title { get; set; }
        public string blogContent { get; set; }
        public string author { get; set; }
        public string userID { get; set; }

        public DateTime publishedDate { get; set; }

    }

你当然不需要这里的 foreach 循环。 尝试这个

var model = from b in blogs   
                         join u in users   
                         on b.userID equals u.Id into bj 
                         from b in bj.DefaultIfEmpty()
            select new  BlogViewModel
                {
                    blogID = b.blogID,
                    blogContent = b.blogContent
                    userID = u.userID
                    author =u.Name
                }
            };
return View(model);

您可以 select 使用所需别名的结果的所需字段:

 var result = from b in blogs   
                 join u in users   
                 on b.userID equals u.Id into group1 //join tables blogs with aspnetusers
                             select new    //below is object initliazer
                             {
                                 blogID = b.blogID,  
                                 blogContent = b.blogContent,
                                 userID = b.userID,
                                 author = u.Name
    
                             };

此外,您可以直接在结果中使用select new BlogViewModel而不是select new并且您不需要使用 foreach 来返回 BlogViewModel 项目列表。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM