I've two tables both with composite primary keys. Both have in common one of the primary key's with a foreign key to another table.
The problem is that when i create the migrations, it messes up the foreign keys.
I must use data annotations.
Example:
public class City
{
[Key, Column(Order = 1)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public string CityCode { get; set; }
[Key, Column(Order = 2)]
public string CompanyCode { get; set; }
public string Description { get; set; }
[ForeignKey("CompanyCode")]
public virtual Company Company { get; set; }
}
public class PostCode
{
[Key, Column(Order = 0)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public string Code { get; set; }
[Key, Column(Order = 1)]
public string CompanyCode { get; set; }
public string Description { get; set; }
public string CityCode { get; set; }
[ForeignKey("CompanyCode")]
public virtual Company Company { get; set; }
[ForeignKey("CityCode, CompanyCode")]
public virtual City City { get; set; }
}
- PostCode and City have a composite primary key (Code, CompanyCode).
- PostCode has a foreign key to the table City (CityCode, CompanyCode).
The problem is that the CompanyCode is part of the primary key and at the same time is part of the composite foreign key to City.
When i say that it messes up the foreign keys i mean the following:
CONSTRAINT [FK_dbo.PostCodes_dbo.Companies_CompanyCode] FOREIGN KEY ([CompanyCode]) REFERENCES [dbo].[Companies] ([CompanyCode]) ON DELETE CASCADE,
CONSTRAINT [FK_dbo.PostCodes_dbo.Cities_CompanyCode_CityCode] FOREIGN KEY ([CompanyCode], [CityCode]) REFERENCES [dbo].[Cities] ([CityCode], [CompanyCode])
In the second constraint, it references CompanyCode with CityCode and CityCode with CompanyCode.
I can't find any example in the internet with any scenario like this.
Where am i wrong?
Thanks in advance.
Edit 1
Between City and Company there is a simples primar key CompanyCode. The same for PostCodes and Company.