简体   繁体   中英

Entity Framework AddObject to only “INSERT INTO” certain columns

We have a system that will use the same code to communicate with different client databases. These databases will use the same EF Model, but different connection strings.

Our problem is, not every site will be using the same version of our database structure; some might be missing a few columns or contain a few old columns.

If we upgrade the system to the current version, now the database model now has an extra EmergencyContact column. All older databases will now fail, because EF is trying to insert into this column (even though we have not set a value for this property).

Is there a way of telling EF to only use columns for which we have a value for, when it generates the INSERT INTO query?

In the case where your model does not match your database schema, EF will only insert/update the columns in the model. However, if the unknown columns are not null, EF will throw an exception. Also, if you created relational constraints on the unknown columns, of course those will not be created as they are not yet known.

If the persistence layer per site is the only part that changes then I would extract your EF model into it's own version eg

DbV1.dll
DbV2.dll

You could then load in the appropriate DLL based on some setting from the client ie you could pass information as a custom header eg

db-version: 1

There are other more reliable ways, however, I don't know what your current setup is like so it's difficult to answer.

EF will be fine if your schema has missing columns that are in the real database, but it will not work if you have columns in the schema that are not in the database, and there is no way to fix that.

Your only choice is to use different schemas for different databases, and write code that manages them (ie, only instantiates the version of the context you need).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM