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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.