开发者

Linq join query displayed in MVC view

I'm trying to display a linq join query in a partial web view.

Here is my query within my controller:

public ActionResult InactiveUsers()
        {
            using (ModelContainer ctn = new ModelContainer())
            {
                DateTime duration = DateTime.Now.AddDays(-3);

                var inactive = from usrs in ctn.aspnet_Users
                               where usrs.LastActivityDate <= duration
                               join o in ctn.Groups on
                               usrs.UserId equals o.UserID
                               select new
                      开发者_JAVA技巧         {
                                   usrs.UserName,
                                   usrs.LastActivityDate,
                                   o.PrimaryPhoneNumber,
                               };

                return View(inactive.ToList());
            }

        }

What I'm a bit confused on is what to do next. I'm familiar with adding strongly typed views using models, but what happens in my case where I have a join query?

If anyone could point me in the right direction I'd be very grateful.

Thanks.


One solution is to use the "ViewModel" pattern. Instead of creating an anonymous type create a view model that contains the data you want to display. Simply populate that and pass it to your view.

When using this pattern we create strongly-typed classes that are optimized for our specific view scenarios, and which expose properties for the dynamic values/content needed by our view templates. Our controller classes can then populate and pass these view-optimized classes to our view template to use. This enables type-safety, compile-time checking, and editor intellisense within view templates.


Instead of returning an IEnumerable of anonymous types, you could create a class for the join result and then create a model for it as normal:

            var inactive = from usrs in ctn.aspnet_Users
                           where usrs.LastActivityDate <= duration
                           join o in ctn.Groups on
                           usrs.UserId equals o.UserID
                           select new InactiveUser(usrs.UserName, usrs.LastActivityDate, o.PrimaryPhoneNumber);

With an InactiveUser class which has a constructor which takes a UserName, Date and PhoneNumber.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜