LINQ2SQL:在子对象中使用父ID两次 - 父ID等于零

时间:2013-06-18 10:32:46

标签: c# linq linq-to-sql

我有以下代码,我希望将AssignmentID和ToDoAssignmentID设置为相同的值。将AssignmentID设置为workOrder.AssignmentID可以正常工作,但将ToDoAssignmentID设置为workOrder.AssignmentID会导致ToDoAssignmentID设置为0.为什么会这样?

workOrder.ClientID = this.Client.ClientID;
workOrder.AssignmentID = this.WorkOrderID;
workOrder.AssignmentNumber = this.GetNextWorkOrderNumber(this.Client);
workOrder.CustomerID = this._CustomerID;
workOrder.DateCreated = this.Created;
workOrder.DatoAvtaltStart = this.AgreedStart == DateTime.MinValue ? new DateTime().MinSDTValue() : this.AgreedStart;
workOrder.DatoAvtaltSlutt = this.AgreedEnd == DateTime.MinValue ? new DateTime().MinSDTValue() : this.AgreedEnd;
workOrder.DateStopped = this.Ended == DateTime.MinValue ? new DateTime().MinSDTValue() : this.Ended;
workOrder.CreatedByEmployeeID = this._CreatedByEmployeeID;
workOrder.ResponsibleEmployeeID = this._ResponsibleEmployeeID;
workOrder.KoordinatorAnsattId = this._CoordinatorEmployeeID;
workOrder.Description = this.Description;
workOrder.Notes = this.Notes;
workOrder.EstimertTimerFra = this.EstimatedHoursFrom;
workOrder.EstimertTimerTil = this.EstimatedHoursTo;
workOrder.EstimatedBillingDate = this.EstimatedBillingDate;
workOrder.Priority = (byte)this.Priority;
workOrder.OBS = this.OBS;
workOrder.CustomerReference = this.CustomersReference;
workOrder.InterntOrdrenr = this.InternalOrderNumber;
workOrder.EksterntOrdrenr = this.ExternalOrderNumber;
workOrder.AssignmentStatusID = this.WorkOrderStatusID;

foreach (var activity in this.Activities)
{
    var ProductID = 0;

    try
    {
        ProductID = activity.Product.ProductID;
    }
    catch (Exception ex)
    {
    }

    workOrder.Activities.Add(new Activity()
    {
        ActivityID = activity.ActivityID,
        ClientID = activity.Client.ClientID,
        AssignmentID = workOrder.AssignmentID,
        Description = activity.Description,
        Notes = activity.Notes,
        IsBillable = activity.Billable,
        Priority = (byte)activity.Priority,
        ActivityTypeID = activity.ActivityType.TypeID,
        PerformedByEmployeeID = activity.PerformedByEmployee.EmployeeID,
        ProductID = ProductID,
        ToDo = activity.IsPlanned,
        ToDoAssignmentID = workOrder.AssignmentID,
        ToDoCustomerID = workOrder.CustomerID
    });
}

workOrderContext.SubmitChanges();

1 个答案:

答案 0 :(得分:0)

关键是不要考虑数据库风格,而是考虑ORM风格。

因此,不是设置键,而是分配实体。

所以改变

ToDoAssignmentID = workOrder.AssignmentID

到(最可能猜到的表名,检查你的实体的定义)下面的实体分配

ToDoAssignment = workOrder

这也将在SubmitChanges期间处理。