C# 在EF5中生成连接两个类的结果
在我的项目中,我有两个类C# 在EF5中生成连接两个类的结果,c#,.net,wpf,ef-code-first,entity-framework-5,C#,.net,Wpf,Ef Code First,Entity Framework 5,在我的项目中,我有两个类ProductCategory和Product public class ProductCategory { [Key] public int CategoryId { get; set; } [Required] public string CategoryName { get; set; } public ObservableCollection<Product> Products { get; set; } }
ProductCategory
和Product
public class ProductCategory
{
[Key]
public int CategoryId { get; set; }
[Required]
public string CategoryName { get; set; }
public ObservableCollection<Product> Products { get; set; }
}
public class Product{
[Key]
public int ProductId { get; set; }
[Required]
public string ProductName { get; set; }
[Required]
public int CategoryId { get; set; }
public virtual ProductCategory ProductCategory { get; set; }
}
请告诉我去这件事的正确方法
谢谢。您可以将投影与选择一起使用:
var objects = context.Products
.Select(p => new
{
ProductId = p.ProductId,
ProductName = p.ProductName,
CategoryId = p.CategoryId,
CategoryName = p.ProductCategory.CategoryName
})
.ToList();
尝试谷歌“linq加入实体”:
var objects = context.Products
.Select(p => new
{
ProductId = p.ProductId,
ProductName = p.ProductName,
CategoryId = p.CategoryId,
CategoryName = p.ProductCategory.CategoryName
})
.ToList();