I had these classes
public class Bid : ...
{
...
[Required]
public virtual TraderUser Trader { get; set; }
}
public class TraderUser : ...
{
...
}
I then changed these classes in the following way and added a new class
public class Bid : ...
{
...
[Required]
public virtual TraderUser TraderUser { get; set; }
}
public class TraderUser : ...
{
...
public int TraderCompanyId { get; set; }
[ForeignKey("TraderCompanyId")]
public virtual TraderCompany TraderCompany { get; set; }
}
public class TraderCompany : ...
{
...
}
When I did an update-database I got the following error
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_dbo.Bid_dbo.TraderUser_TraderUser_Id". The conflict occurred in database "LeasePlan.Development", table "dbo.TraderUser", column 'Id'.
I can't get the database to update. Any help is much appreciated.
Delete your Migrations folder. Create a new migration and generate a SQL script for it. In your database, delete all rows from the migrations history table. Insert a single row into the migrations history, to record that the first migration has already been applied, since your tables are already there.
If you don't care about relationship of existing data. You can use With NoCheck with alter table statement and it will ignore the check to validate data and create Foreign Key Constraint. Once the Foreign Key Constraint will be created, it will enforce integrity for any new records inserted.
Do not know if it is too late, but I had same problem and maybe this could help you.
I cannot see from your post, but probably your TraderUser table has some rows already inserted. What you are trying to accomplish is to create new table TraderCompany and create foreign key relationship in TraderUser that points to TraderCompany table.
In one migration you are trying to create non nullable foreign key relationship for table that already contains data.
You could try to the following:
First migration - everything same, except this line
public int TraderCompanyId { get; set; }
should be
public int? TraderCompanyId { get; set; }
This will allow you to create nullable foreign key column.
Update your TraderCompanyId column for existing data with some row from TraderCompany table.
Second migration - Change code from
public int? TraderCompanyId { get; set; }
to
public int TraderCompanyId { get; set; }
and run your migration.
I hope this will help you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With