Entity Framework Include related table when table is empty

.net c# entity-framework entity-framework-6 entity-framework-6.1

Question

I'm reading data from database to gridview's datasource. My Table2 can be empty. When I try to bind columns from Table2 gives me error that doesn't contain that column. I checked the data that was coming from query. There is Table2 but not columns. Just Count = 0.

How can i get columns of related table even if it is empty?

return entities.Table1
        .Include("Table2")
        .Include("Table3  ")
        .Include("Table2.Table4")
        .Where(results => results.ID == anotherId)
        .ToList();

Table1  one to many  Table2
Table3  one to many  Table1
Table4  one to many  Table2
1
1
11/14/2014 9:47:47 AM

Accepted Answer

When you use EF Table1, Table2, etc. are all classes. Include(string) method is used for caching related records in one query. You can remove Include statements and your query will work similar. So if you don't have any realted records in your DB between Table1 and Table2, then you get count = 0 for Table2 property.

Add some related records to your DB to Table1 and Table2 and execute your query again. Table2 is not DataSet or DataTable, but class.

I think event that .Include("Table2") is redundant if you use .Include("Table2.Table4")

Notice, that Table2 should have FK to Table1 if you want one-to-many relation.

EDITED

If you use EF you don't have to use joins to collect data from few tables. But you have to have FKs well defined. You just use var collction = table1.Table2 to get all Table2 objects related to table1 object.

1
11/14/2014 10:48:52 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow