O
O
oevzbzse2017-09-25 22:52:21
C++ / C#
oevzbzse, 2017-09-25 22:52:21

How to display related data in Entity Framework?

Something I'm already confused about the Entity Framework. I'm learning EF, I made a database using Model-first, a piece of the database on the screen 38bf834b8f48429180e3f406ce6fbc0f.PNG.
How to display fields in datagridveiw, for example, title, price, and category name?
If used ProductGrid.DataSource = db.ProductSet.ToList();then it outputs System.Data.Entity.DynamicProxies.Category.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Kuznetsov, 2017-09-26
@oevzbzse

I would do like this:
1) I would declare a view class

class ProductDto
{
    [System.ComponentModel.DisplayName("ID")]
    [System.ComponentModel.Browsable(false)]
    public int ProductId { get; set; }
    
    [System.ComponentModel.DisplayName("Наименование")]
    public string ProductName { get; set; }
    
    [System.ComponentModel.DisplayName("Цена")]
    public float ProductPrice { get; set; }
    
    [System.ComponentModel.DisplayName("Категория")]
    public string Category { get; set; }

    [System.ComponentModel.DisplayName("Категория (ID)")]
    [System.ComponentModel.Browsable(false)]
    public int CategoryId { get; set; }    
}

I would get entries:
var dtos = (db.ProductSet.Include(x=>x.Category)
.Select(x => new ProductDto { 
   ProductId = x.ProductId, 
   ProductName = x.ProductName,
   ProductPrice = x.ProductPrice,
   Category = x.Category.CategoryName,
   CategoryId = x.Category.CategoryId
})).ToArray();

Well, it would already be tied to DataSoure, through the BindingSource class

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question