简体   繁体   中英

DbUpdateException (insert statement conflicted with foreign key constraint) when adding image (byte array) to database

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM