In my project I have two classes ProductCategory
and 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; }
}
In my UI, there is an form to create products under categories. The form includes 2 ComboBoxes. One for product ID and one for Category (Value member - category id, display member - category name). And another text box for product name. And a ListView for displaying products with their category names.
My question is; I want to retrieve an object collection that includes these fields (to display in the ListView).
ProductID, ProductName, CategoryID, CategoryName
Please tell me the right way to this thing.
Thanks.
You can use a projection with Select
:
var objects = context.Products
.Select(p => new
{
ProductId = p.ProductId,
ProductName = p.ProductName,
CategoryId = p.CategoryId,
CategoryName = p.ProductCategory.CategoryName
})
.ToList();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.