开发者

WinForms & Entity Framework: Display child entity data in WinForms parent data grid view

Let's say I have these two tables:

Category

Id int primary key,
Name nvarchar(50) not null,
Description ntext null,
AnotherColumn nvarchar(20) not null,
AndYetAnotherColumn nchar(10) null

Product

Id int primary key,
CategoryId int not null (references Category.Id),
Name nvarchar(20) not null
OtherStuff...

I have a Product entity that has a navigational EntityReference of type Category, i.e. one product can belong to only one category but one category may have many products.

Let's say I want to display products in a grid, but I want to also display the Category.Name and Category.AndYetAnotherColumn in along with the product information in the products data grid.

If I simply bind the DataGridView control to the Products entity object, it displays a column named Category that binds to the Category navigational property, and the cells in each row for this column display the System.Type of the Category class, which happens to be MyProjectNamespace.Category.

How do I, without creating and binding with another ViewModel or Repository or some custom class that returns m开发者_开发知识库e the hybrid data I need, display this stuff into a data grid? It is a project requirement that I do not create a ViewModel or a middle class.


Use the code like the following:

Entities db = new Entities();
var q = from it in db.Products
        select new
        {
          it.Id,
          it.Name,
          it.OtherStuff,
          it.Category.Name,
          it.Category. AndYetAnotherColumn
        };
dataGridViewInstance.DataSource = q.ToList();


Another solution is create a View in your database, and use EntityFramework to mapping as a new entity

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜