How should I write this Entity Framework query?

I have two tables, Product and ProductCategories. A product can only have one category type. I need to query the database and find the product category for the given ProductID. The Product table has a column called ProductCategoryID, and the primary key of ProductCategories is ProductCatrgoryID. This is what I've tried so far but I get:

Models.Product does not contain a definition for "ProductID"

And the code:

    public ProductCategory GetProductCategory(int id)
    {
        var products = db.ProductCategories
            .Where(c => c.Products.ProductID == id)
            .FirstOrDefault();

        return products;
    }

This goes by Looking for ProductCategories that have a product with the ID:

public ProductCategory GetProductCategory(int id)
{
    var products = db.ProductCategories
        .Where(c => c.Products.Any(p=>p.ProductID == id))
        .FirstOrDefault();

    return products;
}

This goes by finding the product, then returning it's ProductCategory:

public ProductCategory GetProductCategory(int id)
{
    var product = db.Products
        .Include(p=>p.ProductCategory)
        .First(p=>p.ProductID==id);

    return product.ProductCategory;
}
链接地址: http://www.djcxy.com/p/37494.html

上一篇: 数据库设计:如何支持多

下一篇: 我应该如何编写这个实体框架查询?