How not to load navigation properties in datagridview using Entity Framework?

24 Views Asked by At

I use VS 2022. I'm trying to create a Windows Forms project in .NET 4.7.2 with Entity Framework.

I have a database in SQL Server of a bookshop. I used database-first mode in Entity Framework.

I want to display books in a datagridview, but I get extra columns of navigation properties and exceptions.

I'm trying to use this

using(BookshopEntities db = new BookshopEntities())
{
    db.Books.Load();
    this.dataGridView1.DataSource = db.Books.Local.ToBindingList();
}

But I get in my table all columns that I need and in addition all columns with navigation properties.

I tried this Configuration.LazyLoadingEnabled = false; but it doesn't work in a way I want. There are still extra columns, but empty and without exceptions. I don't want to upload to the datagridview properties columns. Only columns from database table.

I used this as a spigot

using(BookshopEntities db = new BookshopEntities())
{
    db.Configuration.LazyLoadingEnabled = false;
    db.Books.Load();
    this.dataGridView1.DataSource = db.Books.Local.ToBindingList();
    dataGridView1.Columns["Authors"].Visible = false;
    dataGridView1.Columns["Genres"].Visible = false;
    dataGridView1.Columns["Publishers"].Visible = false;
    dataGridView1.Columns["BooksSeries"].Visible = false;
    dataGridView1.Columns["Sales"].Visible = false;
    dataGridView1.Columns["BooksDiscounts"].Visible = false;
}

But I think it is a shitcode.

Also, it would be nice if I could edit the table in datagridview and save all the changes in the database. But I can create separate form for editing a single book and that's all.

Of course I can use DataTable and SqlCommand classes to do this, but EF does not require writing SQL queries. Should I use SqlCommand or EF for this problem?

0

There are 0 best solutions below