MVC/EF Code First ICollection 对象

MVC / EF Code First ICollection Objects

我正在使用 MVC5 Code First 并且有几个 classes 看起来像;

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; }
}

我想要 return 一个列出具有特定类别的所有资产的视图。我希望得到类似

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

        return View(model);
    }

我知道我从我的种子方法中获得了一些资产,这些资产具有现有的类别。但是编译器说 "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.

我不完全明白它想告诉我什么。我确实有对我的模型的引用,因为我可以在控制器中的其他地方引用它们。我知道单个资产可能属于多个类别,因此我在 class 级别创建了 ICollection。

这是我的上下文class;

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

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

有人可以帮助我了解如何获取基础数据吗?我正在尝试学习 EF/MVC,非常感谢任何帮助。 谢谢

您无法从类别集合中获取类别名称,您需要检查集合中每个类别的名称。

尝试改用此查询:

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