UPDATE语句与FOREIGN KEY约束冲突

时间:2016-02-11 09:44:17

标签: c# entity-framework asp.net-mvc-5 asp.net-identity

这是我的用户(基于ASP身份):

public class ApplicationUser : IdentityUser
{
    [Required]
    public string FirstName { get; set; }
    [Required]
    public string LastName { get; set; }
    [Required]
    public string StreetName { get; set; }
    [Required]
    public string StreetNumber { get; set; }
    [Required]
    public string HouseNumber { get; set; }

    public string WeekendShippingStreetName { get; set; }
    public string WeekendShippingStreetNumber { get; set; }
    public string WeekendShippingHouseNumber { get; set; }

    public ICollection<Order> Orders { get; set; }
}

这是我的订单对象:

public class Order
{
    public int OrderId { get; set; }

    public string OrderNumber { get; set; }

    public DateTime? FirstDeliveryDate { get; set; }
    public DateTime? LastDeliveryDate { get; set; }

    public DeliveryHours DeliveryHours { get; set; }


    public string Remarks { get; set; }

    public string ApplicationUserId { get; set; }

    public ApplicationUser ApplicationUser { get; set; }

    public InvoiceData InvoiceData { get; set; }

    public bool TermsOfUseAgreement { get; set; }

    public bool Agreement2 { get; set; }

    public DateTime OrderDate { get; set; }

    public Diet Diet { get; set; }

    public decimal TotalAmount { get; set; }

    public bool WantsInvoice { get; set; }

    public bool WantsOtherWeekendAddress { get; set; }

    public bool IsTest { get; set; }

    public bool IsPaid { get; set; }

    [NotMapped]
    public string Password { get; set; }

    public bool IsDeleted { get; set; }
}

当我尝试使用我的存储库方法时:

    public void Delete(string orderNumber)
    {
        try {
            Order order = context.Order.Where(a => a.OrderNumber == orderNumber).FirstOrDefault();

            order.IsDeleted = true;
            order.ApplicationUserId = order.ApplicationUser.Id;

            context.Entry(order).State = System.Data.Entity.EntityState.Modified;

            context.Users.Attach(order.ApplicationUser);
            //context.Order.Add(order);

            context.SaveChanges();
        }
        catch(Exception exception)
        {

        }
    }

我收到错误:

  

保存不公开其关系的外键属性的实体时发生错误。 EntityEntries属性将返回null,因为无法将单个实体标识为异常源。

内部异常如下:

InnerException  {
    "The UPDATE statement conflicted with the FOREIGN KEY constraint 
    \"FK_dbo.Orders_dbo.AspNetUsers_ApplicationUserId\". The conflict occurred 
    in database \"aspnet-Dietetyka-20160128071228\", table \"dbo.AspNetUsers\", 
    column 'Id'.\r\nThe statement has been terminated."
}  System.Exception  {System.Data.SqlClient.SqlException}

我实际上已经失去了理智,我似乎已经尝试了一切......

0 个答案:

没有答案