Robert
Robert

Reputation: 1638

Linq to Entities, ViewModel - DateTime

I have a db table with a start date DateTime field (SQL Server). In my repository I have a "get all" method that returns all the columns. I also have a viewmodel with a DateTime Startdate field.

Repository property:

    public IQueryable<Module> LeadershipModules
    {
        get
        {
            return from module in context.Modules where module.ModuleTypeId == 2 select module;
        }
    }

In my controller, how do I set the StartDate field to a DateTime object?

My controller

    public ActionResult Leadership()
    {
        var viewModel = new LeadershipModulesViewModel
        {
            LeadershipModules = repository.LeadershipModules,
            StartDate = **???**

        };

        return View(viewModel);
    }

When I tried the following:

StartDate = from startDate in repository.LeadershipModules where startDate.StartDate > DateTime.Now select startDate

I get the error below error message

Error 1 Cannot implicitly convert type 'System.Linq.IQueryable<Domain.Module>' to 'System.DateTime' Controllers\ModuleController.cs 41 117 WebUI

What am I doing wrong?

Upvotes: 0

Views: 177

Answers (2)

Ufuk Hacıoğulları
Ufuk Hacıoğulları

Reputation: 38478

public ActionResult Leadership()
{
    DateTime startDate = DateTime.Now;
    var modules = repository.LeadershipModules.Where(m => m.StartDate > startDate);

    var viewModel = new LeadershipModulesViewModel
    {
        LeadershipModules = modules,
        StartDate = startDate
    };

    return View(viewModel);
}

Upvotes: 1

Steven
Steven

Reputation: 172666

You will have to use the Single(), or First() extension methods. Example:

StartDate = (
    from module in repository.LeadershipModules
    where module.StartDate > DateTime.Now 
    select module.StartDate)
    .First();

The query you defined is an IQueryable<Module> which is basically a collection of Module objects. C# cannot implicitly cast this to a DateTime. You you will have to do the proper mapping, which means select the StartDate object, not the module. And execute the query and get a single item of the list (the first, the last, the only, the max, the min, etc).

Upvotes: 1

Related Questions