1

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.

nemesv
  • 138,284
  • 16
  • 416
  • 359
MattSull
  • 5,514
  • 5
  • 46
  • 68

1 Answers1

1

Try looking here:

INSERT statement conflicted with the FOREIGN KEY constraint

"The way a FK works is it cannot have a value in that column that is not also in the primary key column of the referenced table."

If you're adding a record into the table with a FK, you need to make sure the record containing the primary key is there as well.

Community
  • 1
  • 1
Mr. Spock
  • 645
  • 1
  • 9
  • 21
  • Thanks, issue has been resolved by setting FK `reference.UserId = tenantRepository.GetLoggedInTenant().UserId;`. For some reason I didn't think I had to explicitly set the FK myself. – MattSull Mar 26 '13 at 13:40
  • 4
    I would be happy for you, but I'm a Vulcan and incapable of showing human emotions. – Mr. Spock Mar 26 '13 at 16:44