Update-database with code first and foreign key that's required not working - ef-code-first

When using code first i have this scenario:
I have an existing database where tables are created with Code first.
Know suddenly there needs to be a change in the program and there is a new table that is related to the Primary table (with existing data in it).
Example there is a table "Package" and a the new table is "PackageState"
Steps
Create new domain Packagestate with some properties.
Add property packagestate (FK) in Package domain.(P) Note that the packagestate is required.
In the seeding class i add some data for the packagestate
From this point i have a problem, because the value is required, and the seeding method is only executed after update.
How do you solve this with code first?
Because it's possible that there is a new migration file as well.
I need some feedback on this thanks in advance!

You must make your foreign key nullable and update your database
after that you can run your seed.
and after all you should change your foreign key to not null.

Related

Npgsql: Discrepency with Guids between Database.Migrate and Database.EnsureCreated

In a netstandard20 project, I'm using Npgsql.EntityFrameworkCore.PostgreSQL 3.1.0 and I'm having an issue using Guid as the type for my primary keys. If I use Database.EnsureCreated() to create the schema, the primary key columns get created with data type uuid. With everything the same except changing it to use Database.Migrate() creates all the primary key columns with data type text and then I get exception: Npgsql.PostgresException : 42883: operator does not exist: text = uuid when I try to perform any operations.
There is a single migration in my project to create the initial database. In that migration and also in the "context model snapshot" that are auto-generated, the primary key columns are all defined as Guid.
I need to both use the Database.Migrate() method to create the database and also have it create the Guid primary key columns as uuid. How can I make sure it creates the columns correctly?
I found this issue and response after posting my question. It led me to the correct answer which was that when I created the migration I was using sqlite. I needed to blow away the migration created against that data provider and regenerate it.

Entity framework error "Invaid column name" while update record after renaming table

I am using asp.net 4.5 with EF to add/update/delete record.
I renamed a database table StatusMaster to Status.
To reflect this change in entity, I have used "update model from database" in which I have deleted the table first.
Then I have deleted the table from the diagram using "Delete Model".
Then I added table to the edmx file using "Update Model from Database".
I also have update related code in application.
Now Add() method is working well but while update method it gives me error "Invalid column name 'Id'". This column was the primary key before I update but I have also renamed it to "StatusId" but I don't think it should affect it because I already have deleted and added the table using "Update model from database".
Please help me.
All the more reason I prefer code first. More work to set up but easier to make changes down the line. Ill suggest you do the following.
Delete the entire EDMX
Delete Connection Details from config section in Web.config
Re-Create EDMX
I discovered that is faster that trying to debug ur relationship in the EDMX diagram

asp.net Entity Framework/ Update from database/ The table/view does not have a primary key defined and no valid primary key could be inferred

One of the database view I am trying to import using entity framework contains only two columns, one is an integer type of column and another one is an aggregate function. I am getting the following error.
The table/view 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.
I understand it is a known scenario and it can be fixed by either including a Key column in the view or modifying the edmx file manually.
I just wanted to know if there is some other solution other than the above two? I do not want to include an additional column in my query and making changes in edmx is not feasible as DB changes are very frequent and the edmx will be overwritten every time I update from db.
You can mark both properties as entity key directly in the designer but you must ensure that the composite value of these two properties will be always unique. If you cannot ensure that you must add another unique column anyway or you may have some other problems when working with such entity set.

How can this scenario cause an UpdateException in EntityFramework while calling SaveChanges?

I am unable to understand the line in bold from this msdn page:-
http://msdn.microsoft.com/en-us/library/bb738618.aspx
SaveChanges can generate an UpdateException when an object added to the ObjectContext cannot be successfully created in the data source. This can happen if a row with the foreign key specified by the relationship already exists. When this occurs, you cannot use Refresh to update the added object in the object context. Instead, reload the object with a value of OverwriteChanges for MergeOption.
In a table, a foreign key column can have a single value multiple times. e.g. DepartmentID foreign key in Users Table: More than one User can have same DepartmentID foreign key.
So how can this cause an UpdateException ?
Easy. You have an entity in your context in the Added state with a PK value of something already in the DB. This is common when people try to use stub objects incorrectly. If you want more help than that, you need to isolate your problem and post your code.

It has a DefiningQuery but no InsertFunction element... err

This thing is driving me crazy, and the error is quite meaningless to me:
Unable to update the EntitySet 'TableB' because it has a DefiningQuery and no element exists in the element to support the current operation.
My tables are put like this:
TableA
int idA (identity, primary key)
...
TableB
int idA (FK for TableA.idA)
int val
TableB has no defined primary key in the SQL server. The Entity Framework has imported the table and the association and set both fields as key. But it will output that error when I try to do an insert into the table!
What's wrong??
Edit:
As suggested by Alex, the solution was this:
Right click on the edmx file, select Open with, XML editor
Locate the entity in the edmx:StorageModels element
Remove the DefiningQuery entirely
Rename the store:Schema="dbo" to Schema="dbo" (otherwise, the code will generate an error saying the name is invalid)
Remove the store:Name property
I left the key as it was, since it was OK to me that both the columns are part of the key.
Well when a table is encountered without a PrimaryKey it is treated as a View.
And views show up in the EDMX file (open in an XML editor to see) in the StorageModel\EntitySet[n]\DefiningQuery element.
When you have a DefiningQuery the Entity becomes readonly unless you add modification functions. You need 3 modifications functions (aka Stored Procedures) one for each of Insert, Update and Delete.
But you have two options:
Change the key definion:
And convince the EF that what it thinks is a view is really a table
Or add the appropriate modification functions
In your case I recommend (1).
Just Add a primary key to the table. That's it. Problem solved.
ALTER TABLE <TABLE_NAME>
ADD CONSTRAINT <CONSTRAINT_NAME> PRIMARY KEY(<COLUMN_NAME>)
I was missing a primary key on my table and got this error message. One thing I noted was after I added the key to the table, I needed to clear the table from the edmx using the designer, save the edmx, then update it again to add the table back in. It wasn't picking up the key since it was already assigned as a view. This didn't require editing the edmx manually.
Add primary key to table, delete the model from the edmx model, then select update from database, build and run...... works
#Palantir. Verify that both of you tables have Primary Keys set, and be careful with multiple primary keys set in a table.
You need to manually open the .EDMX file in notepad or notepad++ or
in any text editor of your choice.
Locate the entry in edmx:StorageModels in file opened in step1.
Find the DefiningQuery element and remove this tag entirely.
Find the store:Schema="dbo" to Schema="dbo" (if you skip this step
it will generate error of the name is invalid).
Save and close the file.
Hope it will solve the problem.

Resources