I would like to add a new table and a foreign key of an existing table in SQL Server with code first automatic migrations. The only problem I have is that there is data in the table and I can't set the foreign key to a default value for existing data.
Exemple :
Cars table
NameColor
MatrixBlue
CamryRed
Now I want to add the Brand table :
Cars table
IdNameColorBrandId
1MatrixBlue1
2CamryRed1
Brand table
IdName
1Toyota
The question is : How can I set the default BrandId to 1 in my Model Car without having a foreign key constraint error when I run Update-Database command?
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_dbo.Cars_dbo.Brands_BrandId". The conflict occurred in database "Example", table "dbo.Brands", column 'Id'.
For now, In my Configuration.cs file, I add my car brands like this :
context.Brands.AddOrUpdate(
new Brand{ Id = 1, Name = "Toyota" }
);
In My context, I override protected override void OnModelCreating ( DbModelBuilder modelBuilder ) and apply this relation :
modelBuilder.Entity<Car>().HasRequired<Brand>(t => t.Brand);
In my Car model :
[Required( ErrorMessage = "The brand is mandatory" )]
public int BrandId { get; set; }
[ForeignKey( "BrandId" )]
public virtual Brand Brand { get; set; }
In the constructor of the Car model, I set the default value to the BrandId :
public Car()
{
BrandId = 1;
}