简体   繁体   中英

Unexpected property generated by Entity Framework

I'm developing a winform application using Entity framework. this is my .edmx class diagram

在此处输入图片说明

when I'm getting data from this query,

var empQuery = from emp in db.Publishers 
                       select emp;
List<Publisher> pubList = empQuery.ToList();
dataGridView1.DataSource = pubList;

a column named BOOKs is also returning. i want to stop it. Pleas give me an advice. I'm new to Entity Framework.

Navigation properties are automatically generated based on your table relationships. If you don't want the property you can simply delete it from the EDMX.

However, bare in mind that navigation properties are generally lazily loaded which means even though this property is present it won't actually contain any data until it's accessed.

Assuming you don't want to show a BOOKs column in your datagridview, you need to either manually specify the columns in there or return a different type. You could use an anonymous type like this:

var empQuery = (from emp in db.Publishers 
                select new
                {
                    emp.Id, emp.Name, emp.Year
                }).ToList();
dataGridView1.DataSource = empQuery;

The "column BOOKS" is not a column, it a navigation property. In this case it is a collection of Book entity that are related to the current Publisher entity. I think that you are getting this column BOOKS in your datagrid because you aren't specifying the in datagridView1 which columns you want to show. Remember that if you use the AutogenerateColumns flag in your datagrid ( http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.datagrid.autogeneratecolumns%28v=vs.110%29.aspx ), the datagrid will render a column for every property of entity in the datasource collection. To be more specific, I need to know the scenario in where you are working (ASP.NET, Silverlight, etc.)

The Books property doesn't represent a database column, it represents the relationship Publisher and Book and contains the associated books in the Books table (these are often lazily loaded).

This is how EF (and other ORMs) work. You could edit your model and remove the relationship between the two but if you're doing that you're not making use of one of the key features of EF.

My suggestion would be leave your domain model as it is (as it's correct) and update the column of your Gridview so the property is not displayed.

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