简体   繁体   中英

LINQ query from ViewModel to Controller ViewBag to display in SelectList in View

I am in the process of learning MVC, and it is proving to be quite an admirable foe seeing as how I'm used to web forms.

There are so many things I can do in web forms that I can't seem to replicate in MVC, and if I can I'm so lost when it comes to actually implementing it. But my question is as follow;

I have a table

public partial class Patient
{
    public Patient()
    {
        this.PatientHousings = new HashSet<PatientHousing>();
    }

    public Guid ID {get;set;}
    public string FirstName {get;set;}
    public string LastName {get;set;}
    public bool Incarcerated {get;set;}
    public bool Released {get;set;}
    public bool Deceased {get;set;}

    public virtual ICollection<PatientHousing> PatientHousings {get;set;}
}

And this is a other table

public partial class PatientHousing
{
    public Guid ID {get;set;}
    public Guid PatientID {get;set;}
    public bool CurrentPrevious {get;set;}
    public string Building {get;set;}

    public virtual Patient Patient {get;set;}
}

Okay, so in web forms I would just bind a dropdownlist to a datasource with the proper query. Well I can't do that with MVC, and I have to use the controller which I'm still bashing my head against the wall with.

I've read that I need to create a ViewModel to help me with this, so I've created the following

public class PatientViewModel
{
    public List<Patient> patients {get;set;}

    public PatientViewModel(){
        DATAEntities db = new DATAEntities();
        patients = db.Patients.Include(r => r.PatientHousings.Where(h => h.CurrentPrevious == true)).Where(x => x.Incarcerated == false && x.Released == false && x.Deceased == false && !string.IsNullOrEmpty(x.LastName)).ToList();
    }
}

Now I'm getting this error

The Include path expression must refer to a navigation property defined on the type. Use dotted paths for reference navigation properties and the Select operator for collection navigation properties.

Someone please help. I'm so lost right now it isn't even funny.

To clarify: What I need to do is, create a select list in a view that lists all patients that are not incarcerated, released, or deceased.

I think you cannot use a 'where' inside Include as it isn't one of allowed navigation properties.

https://msdn.microsoft.com/en-us/library/gg671236(v=vs.103).aspx

Is there a way to defined .Where inside .Include

You can try using Select or an expression without it and then filter out further using Where.

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.

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