简体   繁体   中英

Referential Integrity Error Entity Framework 6

I have the following classes (reduced for brevity);

public partial class Installation : AuditableEntity<int>
{
    [Column("InstallationId")]
    [JsonProperty(PropertyName = "installationid")]
    [Key]
    public override int ID { get; set; }


    [ForeignKey("Device")]
    [JsonProperty(PropertyName = "deviceid")]
    public int? DeviceID { get; set; }
    public virtual Device Device { get; set; }
}

and (again reduced for brevity);

 public partial class Device : AuditableEntity<int>
    {
        [Column("deviceid"), Key]
        [JsonProperty(PropertyName="deviceid")]
        public override int ID { get; set; }

        public virtual List<Installation> Installations { get; set; }

        public virtual List<Shipment> Shipments { get; set; }
    }

Now I am trying to create a new shipment which has a device associated with it.

My update mehtod is as follows;

    public override void Insert(Shipment entity)
    {
        if (entity == null)
            throw new ArgumentNullException("entity");

        if(entity.Devices != null)
            foreach (var device in entity.Devices)
                if (device.ID != null && device.ID > 0)
                    _context.Entry(device).State = EntityState.Unchanged;

        _dbset.Add(entity);
        _context.SaveChanges();
    }

In this case the devices associated with it will be existing. However I am getting the error;

A referential integrity constraint violation occurred: The property value(s) of 'Device.ID' on one end of a relationship do not match the property value(s) of 'Installation.DeviceID' on the other end.

Now from drilling down when debugging the issue is that its the foreign key inside the installation object is not being set when it gets the object? (see the screen below). But the actualy Installation.Device is being set? how do I get around this pleasE?

屏幕抓取

It is because you have reversed the correct order of your foreign key reference code. Here:

[ForeignKey("Device")]
[JsonProperty(PropertyName = "deviceid")]
public int? DeviceID { get; set; }
public virtual Device Device { get; set; }

Should instead be

[JsonProperty(PropertyName = "deviceid")]
public int? DeviceID { get; set; }
[ForeignKey("DeviceID")]
public virtual Device Device { get; set; }

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