我有3个型号: Shop,Employee,WorkOrder
商店有许多员工,以及许多工作订单。一切都很有效,直到我想让 WorkOrder 属于商店,同时让一个员工负责完成它。
namespace TicketSystem.Models
{
public class WorkOrder
{
public virtual int WorkOrderId { get; set; }
public virtual int ShopId { get; set; }
public virtual string Description { get; set; }
public virtual Shop Shop { get; set; }
// this breaks it:
public virtual int EmployeeId { get; set; }
public virtual Employee Employee { get; set; }
}
}
结果我收到以下错误:
An exception of type 'System.Data.SqlClient.SqlException' occurred in EntityFramework.dll but was not handled in user code
Additional information: Introducing FOREIGN KEY constraint 'FK_dbo.WorkOrders_dbo.Shops_ShopId' on table 'WorkOrders' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint or index. See previous errors.
真正的问题是:这是否因为这是糟糕的设计而发生?我希望能够按商店和员工列出工单。
答案 0 :(得分:1)
是的!你说的是一个员工有很多工单,一个店有很多员工和很多工单。正如你所看到的,EF变得非常困惑。
我会规范化为单亲/子女关系并从那里开始。如果您从ShopId
中删除WorkOrder
,您仍然可以通过该员工找到哪些工单属于哪些商店:
var workOrderId = 1;
var shop = context
.Shops
.Include("Employees")
.Include("WorkOrders")
.First(x => x.Employees.Any(e => e.WorkOrders.Any(w => w.WorkOrderId == workOrderId)));
无需在工作单上复制员工。