Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
                               {
                                   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.

like image 475
109221793 Avatar asked Nov 30 '10 21:11

109221793


2 Answers

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.

like image 119
Rohan West Avatar answered Sep 20 '22 15:09

Rohan West


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.

like image 43
Jackson Pope Avatar answered Sep 18 '22 15:09

Jackson Pope