简体   繁体   中英

Entity framework Binding to DataGrid wpf trouble

I connected to DataBase with Entity: Entity db = new Entity(); ... Then i add DataGrid to Form and try to recive table from my DataBase

var pp = from asd in db.ABONENT select asd;

MyDataGrid.ItemsSource = pp.ToList();

The result is here: Screenshot

it's display other fields from other linked tables, why ? How to display data only from ABONENT table?

My guess is that you are using a DataGrid to display the content of all your tables. Are you columns definition static or dynamically loaded?

If it's dynamically, I suggest to Remove all columns between every Data Binding.

If it's static, hide the columns you don't wanna display (Visible = false).

In Entity Framework, you have Entities , not Tables . Entity Framework abstracts the relational concept of tables into objects you use within your application. That's what an ORM does.

Because of this, relations between tables are expressed as what is called a Navigation Property in your entities, which is basically a property inside the entity class that represents the associated entity.

My point is.. why do you use an ORM if you intend to expose the tables directly into the UI?. Use plain old ADO.Net for that, or otherwise define your UI in such a way that you don't expose the entire table directly to the user. The user knows nothing about tables. The user understands their business. Therefore your application should know nothing about tables.

I see this as a bad practice from a UX perspective, for example, why should the user see the Id columns such as abonentID and RegionID into their UI?? they don't care about that, nor do they understand that. row IDs are a RDBMS concept, not a business concept.

My suggestion: Rethink your approach: either fallback to using plain old ADO.Net, or set the AutoGenerateColumns to false in the DataGrid and expose only the columns the user cares about.

You can select the exposed properties of the entities by using the following syntax:

var pp = from asd in db.Products
            select new
            {
                asd.Id,
                asd.Name,
                ProductCategory = asd.ProductCategory.Name,
            };
MyDataGrid.ItemsSource = pp.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.

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