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

C# LINQ2SQL:在子对象中使用父ID两次-父ID等于零,c#,linq,linq-to-sql,C#,Linq,Linq To Sql,我有以下代码,我希望将AssignmentID和ToDoAsignmentId设置为相同的值。将AssignmentID设置为workOrder.AssignmentID效果很好,但将ToDoAsignmentId设置为workOrder.AssignmentID会导致ToDoAsignmentId设置为0。为什么呢 workOrder.ClientID = this.Client.ClientID; workOrder.AssignmentID = this.WorkOrderID; work

我有以下代码,我希望将AssignmentID和ToDoAsignmentId设置为相同的值。将AssignmentID设置为workOrder.AssignmentID效果很好,但将ToDoAsignmentId设置为workOrder.AssignmentID会导致ToDoAsignmentId设置为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();

关键不在于考虑数据库风格,而在于ORM风格

因此,您可以指定实体,而不是设置关键点

所以改变

ToDoAssignmentID = workOrder.AssignmentID
要(最可能的表名猜测,请检查实体的定义),请执行以下实体分配

ToDoAssignment = workOrder

这也将在提交更改期间进行处理。

因为实体的id尚未生成。那么为什么AssignmentID设置为workOrder.AssignmentID,而ToDoAsignmentId设置为零?活动表是分配表的子表,这意味着它应该可以正常工作。WorkOrder.AssignmentID最初也设置为0,但由于它是外键字段,因此在SubmitChanges()期间Linq-2-sql会再次更新它