Entity Framework and “ViewModel”

entity-frameworklayersmvvm

Earlier I asked a question about "Entity Framework and layer seperation" and found out that some people use a ViewModel to show their data in the UI.

For example if we got a "Person" table and an "Address" table and I want to show a combination of the two tables. I would then create a ViewModel, lets call it PersonAddress, and show it on the UI.

I have a few questions regarding this:

  1. How do you save the "PersonAddress" object to the database since it does not exist in my EF context?
  2. If I only wanted to show the "Person" object, would I still create an identical "ViewModel" object to the one EF creates for me (without the EF specific properties ofcourse)
  3. Do people use the "EntityState" property and dosent it become useless if you only interact with the "ViewModel"?

Best Answer

How do you best save the "PersonAddress" object to the database since it does not exist in my EF context?

You don't. You save a Person and the attached Address separately (in a transaction, if needed). Loading data and saving data can also be thought as different concerns (see CQRS).

If I only wanted to show the "Person" object, would I still create an identical "ViewModel" object to the one EF creates for me (without the EF specific properties of course)

Yes. Again, this is about separation of concerns.

Do people use the "EntityState" property and dosent it become useless if you only interact with the "ViewModel"?

Depends on what you are doing. A ViewModel models the UI, not your data.

Related Topic