簡體   English   中英

首先更新Entity Framework 6中的現有實體

[英]Updating existing entities in Entity Framework 6 code-first

我在更新實體框架6中的現有實體時遇到問題。

我的通用更新方法如下:

public virtual void Update(T entity)
{
    if (entity == null) 
       throw new ArgumentNullException("entity");

    _context.Entry(entity).State = System.Data.Entity.EntityState.Modified;
    _context.SaveChanges();
}

構造函數在哪里:

protected IContext _context;
protected IDbSet<T> _dbset;

public EntityService(IContext context)
{
    _context = context;
    _dbset = _context.Set<T>();
}

IContext基本上是DbContext的接口。

現在,當嘗試更新時,出現以下錯誤;

InnerException = {“ UPDATE語句與FOREIGN KEY約束\\” FK_dbo.Appointment_dbo.Driver_DriverID \\“發生沖突。沖突發生在數據庫” DEVDB \\“,表\\” dbo.Driver \\“的列'id'中。 \\ n該語句已終止。“}

現在,類(為簡潔起見而減少)為:

public partial class Appointment : AuditableEntity<int>
{
        public override int ID { get; set; }

        [ForeignKey("AppointmentType")]
        public int AppointmentTypeID { get; set; }
        public virtual AppointmentType AppointmentType { get; set; }

        [ForeignKey("AppointmentStatus")]
        public int AppointmentStatusID { get; set; }
        public virtual AppointmentStatus AppointmentStatus { get; set; }

        [ForeignKey("Driver")]
        public int? DriverID { get; set; }
        public virtual Driver Driver { get; set; }

        [ForeignKey("Vehicle")]
        public int? VehicleID { get; set; }
        public virtual Vehicle Vehicle { get; set; }
    }

現在,我嘗試通過兩個實體傳遞結果。

即VehicleID = 1,Vehicle = null,VehicleID = null,Vehicle = VehicleEntity,以及一起。

請參見實體內容示例的屏幕截圖:

調試實體的屏幕截圖

請問為什么會發生這種情況?

發生DriverID是因為DriverID0 ,但是數據庫中沒有ID為0 Driver 由於DriverID是可為空的,所以您可能會放棄使用DriverIDnull

除非在調用Update方法之前先了解會發生什么,否則我無法對此進行詳細說明。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM