D
D
Daniil Sidorov2016-12-18 13:03:10
Database
Daniil Sidorov, 2016-12-18 13:03:10

How to make a selection from the database using the Entity Framework?

Hello, I am using Entity Framework. In my wfa application, there is a DataGridView, to which I set the following DataSource:

productBindingSource.DataSource = context.Products.ToList();
metroGrid1.DataSource = productBindingSource;

If you set it this way, then everything works (adding, changing), but then a problem arises: the table has a menu_id field and I want to display not the menu number, but its name, but with such a selection, I can’t do it.
However, it turns out to get the name of the menu using this query:
var products = context.Products.Select(prd=> new
            {
                prd.id,
                prd.name,
                prd.price,
                Menu = prd.Menu.name
            });
            productBindingSource.DataSource = products.ToList();
            metroGrid1.DataSource = productBindingSource;

But another problem appears, adding, changing stops working for me (an error in this line):
productBindingSource.Add(frm.ProductInfo);
ProductInfo is a property from the 2nd form, which returns an object of type Product:
public Product ProductInfo
        {
            get
            {
                return productBindingSource.Current as Product;
            }
        }

Error text:
Objects added to the BindingSource list must be of the same type.
The error is clear, but I do not understand how to solve it. Thanks in advance.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman, 2016-12-18
@yarosroman

metanit.com/sharp/entityframework/6.2.php

A
AIgin, 2016-12-29
@AIgin

The problem is that the query returns objects of an anonymous class, and when adding and changing, the Product class is passed. To solve the problem, there are two options:
1. Convert the received data from the anonymous class to Product
AsEnumerable() (you can use ToList()) is called to execute the request, without it you will receive an Exception, because EF will not be able to parse such a Select().
2. Added and changed data should be converted from Product to an anonymous class

productBindingSource.Add(
                    new
                    {
                        frm.ProductInfo.id,
                        frm.ProductInfo.name,
                        frm.ProductInfo.price,
                        Menu = frm.ProductInfo.Menu.name
                    });;

But it should be noted that in order to add new records to the database through EF, you still have to then bring the data to classes from the model (Product)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question