Deleting from a join-payload table in MVC, is no fun at all. Similar questions are related to a single foreign key and my situation is unique enough that I warranted it a question for itself (if not, please point me to a reference)
I've got this model (which acts as my joint table with payload - it acts as a join table between ApplicationUser and Car which are both data models)
public class UserHasCar
{
// Foreign keys
[Key, Column(Order = 0)]
public string ApplicationUserId { get; set; }
[Key, Column(Order = 1)]
public int CarId { get; set; }
// Navigation properties
[Required]
public virtual ApplicationUser ApplicationUser { get; set; }
[Required]
public virtual Car Car { get; set; }
// Additional fields
public int YearsDriven { get; set; }
}
public class Car
{
public int ID { get; set; }
public virtual ICollection<UserHasCar> UserHasCars { get; set; }
}
public class ApplicationUser : IdentityUser
{
public virtual ICollection<UserHasCar> UserHasCars { get; set; }
}
The problem exists when I am trying to delete a record (delete a UserHasCar entity from the database). Because a UserHasCar has two foreign keys, after running this code I get the following error:
List<UserHasCar> list = (from t in context.UserHasCars where t.ApplicationUserId == userId select t).ToList();
foreach (UserHasCar car in list)
{
context.UserHasCar.Remove(car); // BOOM!
}
The nasty error is: A referential integrity constraint violation occurred: A primary key property that is a part of referential integrity constraint cannot be changed when the dependent object is Unchanged unless it is being set to the association's principal object. The principal object must be tracked and not marked for deletion.
My table definition looks like this:
CREATE TABLE [dbo].[UserHasCars] (
[ApplicationUserId] NVARCHAR (128) NOT NULL,
[CarId] INT NOT NULL,
[YearsDriven] INT NOT NULL,
CONSTRAINT [PK_dbo.UserHasCars] PRIMARY KEY CLUSTERED ([ApplicationUserId] ASC, [CarId] ASC),
CONSTRAINT [FK_dbo.UserHasCars_dbo.AspNetUsers_ApplicationUserId] FOREIGN KEY ([ApplicationUserId]) REFERENCES [dbo].[AspNetUsers] ([Id]) ON DELETE CASCADE,
CONSTRAINT [FK_dbo.UserHasCars_dbo.Cars_CarId] FOREIGN KEY ([CarId]) REFERENCES [dbo].[Cars] ([ID]) ON DELETE CASCADE
);
Do I have to do something simple like EntityState.Deleted/Modified to my two foreign keys? I know its complaining about my clustered primary key and how I cannot delete it without removing the references to my foreign keys... I'm sure I'm missing something small here.
EDIT
As I'm looking through more closely, this line List<UserHasCar> list = (from t in context.UserHasCars where t.ApplicationUserId == userId select t).ToList();
isn't pulling in the right ApplicationUser or Car from my database table, all values are null. I can see that the query isn't pulling in the proper ApplicationUser or Car, but why?