fanarek
fanarek

Reputation: 367

Why is my entity framework context not updating after adding column to database?

Basically there's simple application that I've made for EF testing. I added DataModel, then created data source object just like MSDB tutorial says.

DataBinding works good, but problem appears when I add or delete column from sql table (eg. in SSMS ALTER TABLE xxx ADD yyy varchar(50)).

Is it possible to update/refresh data model without me ? I mean, I don't want to run IDE and click "Update Model from Database", because users will add new columns massively. Is Entity Framework even good for this idea ?

Upvotes: 1

Views: 2997

Answers (3)

user3188639
user3188639

Reputation:

It doesn't because it makes no sense and is technically impossible. How would it work? When is this updating supposed to happen? Should a database have a permanent connection to your context and data model and update it whenever schema changes? What happens if you have thousands of connections, what would happen then? Also, do you really expect the change in the database schema to change your c# code? Can database change the compiled code (dll), or just source?

And, apart from these technical questions, your database model is not your domain model. Usually they correlate, but that is not always the case. I had a few applications where c# code had fewer objects than the database had tables and these object didn't need all the columns in the database.

So, no, this would be quite unusable or completely wrong.

Upvotes: 2

MindSwipe
MindSwipe

Reputation: 7885

In Entity Framework you have two choices.
1. Create a Database and generate a Model from it
2. Create a Model and generate a Database from it

Entity Framework does not do this in real time, optimally you choose one you want to use and do it once, you can always delete the old Database and generate a new one (if using option 2) or delete the Model and generate a new one (when using option 1)

Option 1 is called a "Database first" approach, meaning that any changes to the data model are done in the Database and your Model has t be adjusted/ regenerated
Option 2 is called a "Code First" approach, meaning changes to the data model are done in the Code classes and be migrated to the Database

Upvotes: 1

RoelA
RoelA

Reputation: 601

Im assuming you are using the 'database first' aproach based on your question, if so; have a look at this link.

If you are using a 'code first' approach, then have a look at migrations.

Upvotes: 0

Related Questions