A DbUpdateException is being thrown at db.SaveChanges()
in my UploadReferencePhoto ActionResult
when I try to upload a photo to a SQL database via my application. I'm using code first with table-per-type inheritance. Models related to the scenario are as follows:
UserProfile:
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
// ...
}
Tenant:
[Table("Tenant")]
public class Tenant : UserProfile
{
public Tenant()
{
this.ReferencePhotos = new List<ReferencePhoto>();
}
public virtual ICollection<ReferencePhoto> ReferencePhotos { get; set; }
}
Image:
[Table("Image")]
public class Image
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int ImageId { get; set; }
}
ReferencePhoto:
[Table("ReferencePhoto")]
public class ReferencePhoto : Image
{
// 1:many with Tenant
public int UserId { get; set; }
[ForeignKey("UserId")]
public virtual Tenant Tenant { get; set; }
}
So Tenant
extends UserProfile
and ReferencePhoto
extends Image
. When I click upload aforementioned exception is thrown. Inner exception is as follows:
"The INSERT statement conflicted with the FOREIGN KEY constraint \"FK_dbo.ReferencePhoto_dbo.Tenant_UserId\". The conflict occurred in database \"C:\USERS\HOME\DESKTOP\LETLORD\LETLORD\APP_DATA\LETLORD.MDF\", table \"dbo.Tenant\", column 'UserId'.\r\nThe statement has been terminated."}
Can someone tell me what exactly the inner exception is saying and possibly how to resolve it? Let me know if more code/information needed.