参照完整性错误实体框架6

时间:2015-10-06 06:15:10

标签: c# entity-framework-6

我有以下课程(为简洁而减少);

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; }
}

和(为了简洁而再次减少);

 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; }
    }

现在我正在尝试创建一个与其关联的设备的新货件。

我的更新mehtod如下;

    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();
    }

在这种情况下,与之关联的设备将存在。但是我收到了错误;

  

发生了参照完整性约束违规:属性   关系一端的'Device.ID'值与   另一端'Installation.DeviceID'的属性值。

现在从深入调试问题时,安装对象中的外键在获取对象时没有被设置? (见下面的屏幕)。但实际安装.Device正在设置?我该如何解决这个问题?

Screen grab

1 个答案:

答案 0 :(得分:0)

这是因为您颠倒了外键引用代码的正确顺序。这里:

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

应该是

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