0

Here is part of my Hardware class:

public class Hardware
    {
        public int Id { get; set; }

        public virtual ICollection<HardwareType> HardwareType { get; set; }
         ....
    }

In the sample data that is seeded, Hardware is newed up like this (partially):

new Hardware { ... HardwareType = htype.Where(h => h.HType == "PC").ToArray() }

htype is a List<HardwareType> with various string values for HType, which is the property in the HardwareType class.

In my controller, I am trying to assign a Lambda expression to a variable so I can loop through it in my view. Here is what I have:

private Context db = new Context();  

public ActionResult Index() {
    Hardware Pcs = db.Hardware.Where(h => h.HardwareType == "PC");
}

But the compiler is telling my I can't do that because h.HardwareType is an iCollection. Which makes sense. But how do I write this line of code so that I can pass Pcs to my view?

sehummel
  • 5,476
  • 24
  • 90
  • 137

1 Answers1

0

I've only ever done this where the ICollection is of type string and not a custom type, but the same solution may work for you. You haven't shared your definition of HardwareType, so my syntax may not be 100% correct, but it should give you the idea.

public ActionResult Index() {

    HardwareType hwt = new HardwareType { HType = "PC" };

    Hardware Pcs = db.Hardware.Where(h => h.HardwareType.Contains(hwt));
}

This should give you all Hardware objects that have associated HardwareTypes as you define them. Again, I've only done this with simple strings, but I'm thinking it'll work this way too.

This is a similar question that may be helpful: How to do an "in" query in entity framework?

Community
  • 1
  • 1
Rick B
  • 1,156
  • 10
  • 11
  • I get this error with what you suggested: Error 18 Cannot implicitly convert type 'System.Linq.IQueryable' to 'CIT.Models.Hardware'. An explicit conversion exists (are you missing a cast?). Suggestions? – sehummel Dec 11 '12 at 19:45
  • Got it. `IQueryable Pcs = db.Hardware.Where(h => h.HardwareType.Contains(hwt));` – sehummel Dec 11 '12 at 20:03
  • @sehummel If you didn't want to return an IQueryable, you could do `Hardware Pcs = db.Hardware.Where(h => h.HardwareType.Contains(hwt)).FirstOrDefault();` or 'List Pcs = db.Hardware.Where(h => h.HardwareType.Contains(hwt)).ToList();` depending if you want one or multiple results. – Rick B Dec 11 '12 at 20:06