CaRDiaK
CaRDiaK

Reputation: 885

MVC / EF Code First ICollection Objects

I am using MVC5 Code First and have a couple of classes that look like;

public class Asset
{
    public int Id { get; set; }
    public string FileName { get; set; }
    public virtual ICollection<Category> Categories { get; set; }
}

public class Category
{
    public int CategoryId { get; set; }
    public int AssetId { get; set; }
    public string CategoryName { get; set; }
    public string Description { get; set; }
}

I would like to return a view that lists all Assets that have a particular Category. I was hoping for something along the lines of

    public ActionResult ListByCategory(string categoryName)
    {
        var model =
            from r in _db.Assets
            .Where(r => r.Categories.CategoryName == categoryName)
            select r;

        return View(model);
    }

I know I have some assets from my seed method that have categories that exist. But the compiler is saying "System.Collection.Generic.ICollection Does not contain a definition for CategoryName and no extension method could be found, am I missing a reference?" This is on my .Where line.

I don't fully understand what it's trying to tell me. I do have a reference to my Models as I can reference them elsewhere within the controller. I know that a single Asset might be in several Categories, hence I created the ICollection at the class level.

Here is my context class;

public class AssetsDb : DbContext
{
    public AssetsDb() : base("DefaultConnection")
    {

    }
    public DbSet<Asset> Assets { get; set; }
    public DbSet<Category> Categories { get; set; }
}

Could somebody help my understanding on how I can get to my underlying data? I'm trying to learn EF / MVC so appreciate any help. Thanks.

Upvotes: 0

Views: 423

Answers (1)

Lee D
Lee D

Reputation: 12951

You cannot get a CategoryName from a collection of categories, you need to check the name of each category within the collection.

Try using this query instead:

var model =
        from r in _db.Assets
        .Where(r => r.Categories.Any(c => c.CategoryName == categoryName))
        select r;

Upvotes: 2

Related Questions