简体   繁体   English

将EF5中的两个类别的结果生成

[英]Generating results joining two classes in EF5

In my project I have two classes ProductCategory and Product . 在我的项目中,我有两个类ProductCategoryProduct

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

In my UI, there is an form to create products under categories. 在我的用户界面中,有一个表单可以在类别下创建产品。 The form includes 2 ComboBoxes. 该表格包括2个ComboBox。 One for product ID and one for Category (Value member - category id, display member - category name). 一个用于产品ID,一个用于类别(值成员-类别ID,显示成员-类别名称)。 And another text box for product name. 还有另一个用于输入产品名称的文本框。 And a ListView for displaying products with their category names. 还有一个ListView用于显示带有类别名称的产品。

My question is; 我的问题是; I want to retrieve an object collection that includes these fields (to display in the ListView). 我想检索一个包含这些字段的对象集合(以显示在ListView中)。

ProductID, ProductName, CategoryID, CategoryName

Please tell me the right way to this thing. 请告诉我正确的方法。

Thanks. 谢谢。

You can use a projection with Select : 您可以将投影Select

var objects = context.Products
    .Select(p => new
    {
        ProductId = p.ProductId,
        ProductName = p.ProductName,
        CategoryId = p.CategoryId,
        CategoryName = p.ProductCategory.CategoryName
    })
    .ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM