Referential Integrity Error Entity Framework 6

c# entity-framework-6

Question

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?

Screen grab

1
1
10/6/2015 6:15:09 AM

Popular Answer

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; }
0
10/6/2015 6:49:33 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow