Adding a New Column to an Existing Table in Entity Framework - entity-framework

I have added a new column to a table in my database. The table is already defined in the existing Entity Framework model. I've been through most of the items here on how to do this and it still fails.
A little background, this entity model has not been updated in at least 3 years. So aside from the column I'm adding I know there have been a number of other columns that have been added in that time, but never included. I took over the project about 9 months ago and have never been able to successfully update the model.
First attempt:
Opened the Model in Visual Studio
Right Clicked on the Background
Clicked on "Update Model From Database..."
Clicked on the Refresh Tab
Selected Tables
Highlighted the specific table
Clicked Finish
Result:
Classes for Dozens of tables that were in my model were deleted
The table in question was not updated
Second Attempt
Restored all Source
Same as above but
After opening the Update Wizard, Clicked the Delete Tab
Selected Tables
Clicked Finish
All the Tables were deleted
Saved the EF Model/Closed/Opened it
Went back to the Update Wizard Add Tab
Clicked Tables
None of my tables were displayed when I expanded everything
Checked the checkbox at the Tables level
Result
None of my tables were added back, but anything that was not
originally included was added
Third Attempt
Restored all source
Deleted the two .tt files
Opened the Update Wizard
Clicked Add for Everything
Result
Nothing was recreated, no .tt files or anything else.
Fourth Attempt
Restored Source
Deleted Table from the EF Model
Opened Update Wizard
Clicked Add Tables
Results
Classes for Dozens of tables that were in my model were deleted
The table in question was not added back
Final Attempt
Added entity manually to model
Result
Code all compiled and ran, but values were never retrieved from the DB or updated
Any help or direction that could be provided would be greatly appreciated as I'm at a critical point and have to get the model updated.

The "Update Model from Database" is hard/slow to use and is prone to errors. It generates other stuff that you probably don't want/need. So manually adding the column that you need will work better.
I suggest you do it outside the VS editor since depending on how many models/tables, it can be very slow opening the file in VS.
So in Windows Exlorer, right-click on the *.edmx file and open with Notepad (or Notepad++/Textpad).
Search for the text <EntityType Name="YourTableNameToAddColumn">.
Add the property <Property Name="YourNewColumnName" Type="varchar" MaxLength="64" />
Search for the text <MappingFragment StoreEntitySet="YourTableNameToAddColumn">
Add mapping to the new column <ScalarProperty Name="YourNewColumnName" ColumnName="YourNewColumnName"/>
Save the *.edmx file

Right click on the *.edmx file and open with Visual Studio's XML editor (or Notepad/Notepad++/Textpad).
Search for the text <EntityType Name="YourTableNameToAddColumn">.
Add the property e.g.: <Property Name="YourNewColumnName" Type="varchar" MaxLength="64" /> (these ones are SQL types, see existing columns for an example of how they should look).
Search for the text again <EntityType Name="YourTableNameToAddColumn">, there is a second one.
Add the property e.g.: <Property Name="YourNewColumnName" Type="String" MaxLength="64" FixedLength="false" Unicode="true" /> (these ones are EF types, see existing columns for an example of how they should look).
Search for the text <MappingFragment StoreEntitySet="YourTableNameToAddColumn">.
Add mapping to the new column <ScalarProperty Name="YourNewColumnName" ColumnName="YourNewColumnName"/> (Note: these are in reverse order, newest first)
Save the *.edmx file
After that update the edmx model of your table in the (auto-generated) entity framework .cs files public string YourNewColumnName { get; set; }

An addendum to the answer by alltej above, and answering Chris Walsh's reply that he is getting 'The conceptual side Member or Property 'xxxxx' specified as part of this MSL does not exist in MetadataWorkspace." on the new Scalar property line under '
You have to make sure that you search 'Add the property ' in TWO places within your .edmx file , otherwise you will get Chris's error

Figured out the problem. When I generated the model I was getting an Error 113:
Multiplicity is not valid in Role.
I didn't notice it among the other 16307 errors that were generated when the creation failed. Once I fixed that everything worked fine.
Thanks

I just found this question when I had a situation where I added some columns to a table, and my edmx file would update just fine; however, the code generation was not triggering properly, so my .cs files were not updating. I right clicked on the Entities.tt file and selected "Run Custom Tool" which runs the text transformations, which fixed it for me.

I ran into this problem a while ago and was able to deal with it by removing the particular table from the model, then doing the "Update model from database" step, selecting that table.

Make sure your 'Model.edmx' file has the name same as 'Model.tt' if not, just rename it the same name with the *.tt file. Then delete entities from designer and import again by 'update model from database'.

Related

Can't select the database when updating EF model

I have an edmx model
I right click on it and select Update model from database
The wizard show up .It normally show me Choose Your Data Connexion, but not anymore. Now it show me directly Choose Your Database Objects
How can I select a different database ?
PS: When I create a second edmx in the same project and want to update it, the second one works like it should
After some trials, I found it.
You must delete the connection string in your config file (app.config in my case)

How to update only one table for model from database with Entity Framework?

I have a model generated from db with Entity Framework. When I have any change in database, I update model from database to get the change in model. But this update is applied to all entities (tables) included in model.
Now I add a new column in a table Tab1. I don't want to update model from database as some other changes that I don't want to include in model. I can add the new property in model for entity Tab1 manually. then it caused mapping error.
So I need to update Model.Store for the table to include the new column. It means I want to update model only for Tab1.
How can I do this?
The EDMX file is an XML file that is a combination of 3 different parts that make up the whole thing. If you right-click on your EDMX file and choose "Open with... XML Editor" you'll see the 3 different sections:
<edmx:ConceptualModels>
<edmx:StorageModels>
<edmx:Mappings>
These sections can be edited manually, at your own risk! :-)
That way you can modify only what you need to.
Note that it's also possible to generate CSDL, SSDL & MSL files rather than having them embedded in the binary file, by changing the "Meta Artifact Processing" property of your model to "Copy to Output Directory".
If you don't want to do this manually, there's the Huagati DBML/EDMX tool, it is free and you can download it from huagati official site or from visual studio gallery, which is a Visual Studio plugin that allows you to select what changes need to be done.
I use following (Conditional) trick. This could be done only when no Table depends on the table which you want to update.
Delete the table which needs to be updated.
Right click on Model and select 'Update Model From Database'. The Table would be shown in the tab 'Add'. Select this table and Update the model.
Precaution : If other existing tables have changes in them, EF would update these changes as well.
There is way of doing it automatically.
right click edmx file > update model from data base > Refresh tab > Tables > select the table(you want to update) and press finish that's it.

Why can't I use a View containing a Union in Entity Framework 4.0?

I have a View which looks similar to this:
SELECT Id, Name
FROM Users
UNION ALL
SELECT NULL as [Id], NULL as [Name]
When I try to map to this view in Entity Framework, it just fails. I don't get an error, but the view does not exist in my data store. Why is this? Is there a way around it?
I know this is an older question already marked as answered, but I wanted to post an alternative to editing the edmx. I learned this one the hard way, after tons of Google searches and pulling my hair out for hours, trying different options...
For a view, EF attempts to to infer a primary key by identifying columns that are non-nullable
and non-binary (see Create an Entity Key When No Key Is Inferred).
With a view used to flatten related data for lookup purposes, this can result in many columns (or the wrong ones) being inferred as keys.
For a view with a UNION, it can cause the opposite problem, because there may be no true identity column that can be safely included as a key.
To force EF to identify columns as a key, you can use ISNULL() to ensure the value is non-nullable: ISNULL(column_name, replacement_value)
To force EF to not mark a column as a key, you can use NULLIF() to make it nullable: NULLIF(column_name, value_not_equal_to_parameter_1)
If you need to ensure a value is returned, but don't want to have it marked as a key, I believe COALESCE(column_name, replacement_value) will do the job of ISNULL without EF marking the column as a key
If there is truly no viable column available as a primary key (as in a UNION view), you can fake a non-nullable PK through the use of ISNULL() combined with ROW_NUMBER() in your SELECT statement: SELECT ISNULL(ROW_NUMBER() OVER (ORDER BY sort_criteria), 0) as 'ALIASNAME'
As an alternative, the edmx can absolutely be edited directly as Marcos Prieto suggested, but you run the risk of having those changes overwritten the next time you run "Update Model from Database".
Hope this helps anyone who encounters this in the future!
It is because Visual Studio cannot infers the Primary Key of your View.
You can see the error message within edmx file by open it with XML editor and see the SSDL section.
Here is error message that results from my Model(which I created some View like yours within my Database just to emulate) :
Errors Found During Generation:
warning 6013: The table/view 'PhoneBook.dbo.ContactCustomer' does not have
a primary key defined and no valid primary key could be inferred.
This table/view has been excluded. To use the entity,
you will need to review your schema,
add the correct keys, and uncomment it.
It is not true that Union is not supported in EF 4.
But I think the problem is that Visual Studio saw your view as the odd View.
You can doing some experiment by create another View and compares them (using update model from database menu within model designer).
And you can modify the Model by hand (manual typing the edmx file) to define the Primary Key to resolve this.
I had a view that worked perfectly. I modified it (changed the view on a union of 2 tables), updated the model from database and this problem appeared.
I fixed it in 3 steps:
Open the .edmx file with a XML editor.
Uncomment the view's EntityType XML (edmx:StorageModels > Schema) code and add the Key:
<EntityType Name="your_view">
<Key>
<PropertyRef Name="your_id" />
</Key>
<Property Name="your_id" Type="int" Nullable="false" />
<Property Name="other_field" Type="varchar" MaxLength="45" />
</EntityType>
Be sure that EF didn't erased the view in edmx:StorageModels > Schema > EntityContainer (if you have code repository, copy the code from there):
<EntitySet Name="your_view" EntityType="Your_Model.Store.your_view" store:Type="Views" store:Schema="your_schema" store:Name="your_view">
<DefiningQuery>SELECT
`your_view`.`your_id`,
`your_view`.`other_field`,
FROM `your_view` AS `your_view`
</DefiningQuery>
</EntitySet>
I know this is an old question but i faced this issue recently & after trying to do the above mentioned methods i simply created another view that selects from the Union view & i was able to map the new view by updating my entity model.

Entity Framework: deleted SQL table is not removed from the model

Seemingly simple thing got me completely frozen and I can't find anything on the Net about this:
I had a common many to many relationship in my db:
Table One + TableTwo + LinkingTable with 2 columns: TableOneID and TableTwoID
I deleted the LinkingTable and tried to update the model from database. Now I get error "Error 11007: Entity type 'LinkingTable' is not mapped."
Does anyone know what exactly this EF wants? Thank you!
Right-click the Model in the Solution Explorer. Select "Open with..." Select "XML (Text) Editor" in the dialog. Remove all nodes and references of the LinkingTable (or whatever its real name is) from the model's xml. Close all model files that are currently opened (I know, weird). Build the project. Open the model again. Everything should be fine now.
Open Model Browser,
In the Entity types, select the table which is to be deleted,
It will remove all the associations with the table.
It worked well for me.

EF4 is throwing an error "Schema specified is not valid"

I'm getting a weird EF4 "Entity Framework v4" error when I do a select on the context:
Schema specified is not valid. Errors:
The relationship 'AnalyzerConfigurationModel.FK_AnalyzerMetadataParameters_AnalyzerMetadata' was not loaded because the type 'AnalyzerConfigurationModel.AnalyzerMetadataParameter' is not available.
The query to generate the error is:
Using context As New AnalyzerConfigurationEntities
Dim EFAnalyzerConfiguration = (From P In context.AnalyzerConfigurations
Where P.Name = analyzerConfigurationName).FirstOrDefault
End Using
The schema is show below.
I've checked the connection strings, multiple times, its not that. Everything looks fine. I'm not sure if the XML that gets generated from this schema is off or not. But looked there too and don't see anything off or different from other properties. Has anyone run into this one before?
I found that if I expanded the EDMX file in solution explorer (VS 2012) and right clicked on each .tt file and selected Run Custom Tool also fixed the issue. This might be easier than de
Also make sure you're referencing project has the EntityFramework installed otherwise the dependent code will get this error.
https://www.nuget.org/packages/EntityFramework
Let me explain this:
The problem is because the system did not find consistency of the columns in database, the entities in the .edmx file and the model class and also the use of the same in the controller class.
So follow the following steps to fix this up:
Go to the database, check all the column names and properties.
Confirm them with the class diagram in the.edmx file. Right-click on the class in which you are getting the error, and select update option for the class. Select the Refresh tab in dialogue (if there is no new column added. if new column is added, you can select the add tab.) and select the relevant objects. Generally they are tables. So select them and finish.
Next check the names in the model class and the controller class.
This should be the solution. If not, let me know.
Are you using the SelfTracking Entity T4 template? I had this issue and found out the T4 template was not re-generating my entities after I had changed the Entity model in the Entity Designer. Try to right click the T4 Template and click "Run custom tool", and see if that helps.