实体框架:无法确定关系的主要结束。多个添加的实体可以具有相同的主键

时间:2014-04-27 15:35:27

标签: sql-server asp.net-mvc linq entity-framework linq-to-entities

我在更新模型时收到此错误我正在分享我的代码,请告诉我最佳解决方案。

票务明细类:

public class TicketDetail
{
    [Key]
    public int TicketDetailId { get; set; }
    public int GenericOrderId { get; set; }
    public int PartId { get; set; }
    public int Quantity { get; set; }
    public decimal? CustomerPrice { get; set; }
    public string Status { get; set; }

    [Timestamp]
    public byte[] RowVersion { get; set; }

    public virtual Part Part { get; set; }
    public virtual Ticket Ticket { get; set; }
}

OrderDetailClass:

public class OrderDetail
{
    [Key]
    public int OrderDetailId { get; set; }
    public int GenericOrderId { get; set; }
    public int PartId { get; set; }
    public int Quantity { get; set; }
    public decimal? UnitPrice { get; set; }
    public string Status { get; set; }

    [Timestamp]
    public byte[] RowVersion { get; set; }

    public virtual Part Part { get; set; }
    public virtual Order Order { get; set; }
}

订单类:

public class Order : GenericOrder
{
    public virtual ICollection<OrderDetail> OrderDetails { get; set; }
}

门票类

public class Ticket : GenericOrder
{
    public virtual ICollection<TicketDetail> TicketDetails { get; set; }
}

GenericOrderClass:

public abstract class GenericOrder
{
    [Key]
    public int GenericOrderId { get; set; }
    public string ProcessId { get; set; }
    public DateTime Date { get; set; }
    public string FullName { get; set; }
    public string Email { get; set; }
    public string Company { get; set; }
    public string Phone { get; set; }
    public string Message { get; set; }
    public decimal Total { get; set; }

    [Timestamp]
    public byte[] RowVersion { get; set; }
}

这是控制器类代码

TryUpdateModel(order);
TryUpdateModel(ticket);

try
{
    order.Date = DateTime.Now;
    ticket.Date = DateTime.Now;
    order.ProcessId = DateTime.Now.Ticks.ToString().Substring(12, 6);
    ticket.ProcessId = order.ProcessId;

    //Add the Order
    storeDB.Orders.Add(order);
    storeDB.Tickets.Add(ticket);

    //Process the order
    cart.CreateOrder(order);
    cart.CreateTicket(ticket);

    // Save all changes
    storeDB.SaveChanges();

    //return RedirectToAction("Complete",
    //    new { id = order.QuoteOrderId });
    TempData["OrderSuccess"] = "Your order has been submitted successfully with the Process ID " + order.ProcessId;
    TempData["OrderId"] = order.GenericOrderId;
    TempData["Email"] = order.Email;

    return RedirectToAction("Confirm");
}
catch (Exception e)
{
    //Invalid - redisplay with errors
    ModelState.AddModelError("", e.Message);
    return View(order);
}

我搜索了互联网,但找不到任何解决方案。

1 个答案:

答案 0 :(得分:0)

尝试保存订单和故障单,保存后添加详细信息。