0

如果我想执行基于多个表之间的连接的查询,那么如何使用 Entity Framework 4.1 以代码优先的方法对其进行编码?例如,我想执行以下查询:

SELECT p.ProductId
 , p.Name AS ProductName
 , c.Name AS CategoryName
FROM
Products p
INNER JOIN Categories c
    ON c.CategoryId = p.CategoryId
4

1 回答 1

1

您将创建如下类:

public class Product {
    public int ProductId { get; set; }
    public string Name { get; set; }
    public int CategoryId { get; set; }
    public virtual Category Category { get; set; }
}

public class Category {
    public int CategoryId { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Product> Products { get; set; }
}

您将使用此查询,从导航属性自动创建连接:

var query = from p in context.Products
            select new {
                ProductId = p.ProductId,
                ProductName = p.Name,
                CategoryName = p.Category.Name
            };
于 2012-07-24T07:47:13.663 回答