I have an urgent problem that I could not find an answer for the entire network.
I am using CodeFirst EF 4.3.1 and I get the error message: Violation of PRIMARY KEY constraint 'PK_T_CRProviders'. Cannot insert duplicate key in object 'dbo.T_CRProviders'. Violation of PRIMARY KEY constraint 'PK_T_CRProviders'. Cannot insert duplicate key in object 'dbo.T_CRProviders'.
My code is:
Models:
public enum CRProviderEnums { PE_Abcd = 0, PE_Efgh } [Table("T_CRProviders")] public class CRProvider { [Key] [Required] public int Enum { get; set; } [Required] public string Name { get; set; } } [Table("T_CRSupportedResources")] public class CRSupportedResource { [Key] public Guid SupportedResourceId { get; set; } [Required] public CRProvider Provider { get; set; } }
Dbcontext:
public class RSContext : DbContext { public DbSet<CRProvider> CRProviders { get; set; } public DbSet<CRSupportedResource> CRSupportedResources { get; set; } }
The T_CRProviders table is as follows: Enum (PK), Name
The T_CRSupportedResources table is as follows: SupportedResourceId (PK), Provider_Enum (FK).
In the T_CRProviders database table, I already have a provider with the following values:
Enum: 0 (which is PE_Abcd) Name: "PE_Abcd"
Now my main () calls the AddSupportedResource method. This method adds a new CRSupportedResource to the T_CRSupportedResources table, which refers to provider 0 (PE_Abcd). The method is as follows:
public void AddSupportedResource() { CRSupportedResource supportedResource = new CRSupportedResource() { SupportedResourceId = Guid.NewGuid(), Provider = new CRProvider() { Enum = (int)CRProviderEnums.PE_Abcd, Name = "PE_Abcd" } }; using (RSContext myContext = new RSContext()) { myContext.CRSupportedResources.Add(supportedResource); myContext.SaveChanges(); } }
I expect this method to leave the T_CRProviders table intact and add a new row to the T_CRSupportedResources table, which will look like this:
SupportedResourceId: DE532083-68CF-484A-8D2B-606BC238AB61 Provider_Enum (FK): 0 (which is PE_Abcd).
Instead, in SaveChanges, the Entity framework is also trying to add a provider to the T_CRProviders table, and since such a provider already exists, it throws the following exception:
An error occurred while updating the entries. Violation of PRIMARY KEY constraint 'PK_T_CRProviders'. Cannot insert duplicate key in object 'dbo.T_CRProviders'. The statement has been terminated.
My question is:
How can I tell EF not to update the T_CRProviders table after updating the T_CRSupportedResources table?
Btw, in SQL Server, I see that the T_CRSupportedResources table has a foreign key named FK_RW_TCRSupportedCloudResources_RW_TCRCloudProviders_Provider_Enum , and its update rule is set to No Action .