Use ViewModel (Model Binder) in LINQ to Entity Framework – LINQ Doesn’t Return All Joined Data

When using Entity Framework, I’ve found that the join LINQ query that I specified will not return all the data I needed.

Although the query includes OpmaDB.Property entity, the entity is not included in the result object. So, statement like:

_propertyList.FirstOrDefault().Property.PropertyId

will return the famous-‘Object reference not set to an object of an instance’-error:

To resolve this issue, we can use ViewModel, or Model Binder, instead of the entity itself. This should be the better practice anyway. The query looks like:

And the ViewModel looks like this:

Alternatively, we can also store the whole entity model in the View Model instead of property members of the entity. This is how I would do it, the ViewModel:

And the query:

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s