C# 添加具有多个子实体的实体的最佳实践(实体框架)

C# 添加具有多个子实体的实体的最佳实践(实体框架),c#,asp.net,entity-framework,entity-framework-core,C#,Asp.net,Entity Framework,Entity Framework Core,我目前有一个对象报告。此报表对象有多个子实体,例如WorkOrder和ReleaseQuestions。我只是想问一下将WorkOrder和ReleaseQuestions添加到数据库中的最佳实践。当前,在创建报表时,我会将新的空白对象添加到报表对象中,然后将其添加到数据库中。这是因为最终这些组件将由用户填写,所以在数据库中放置空白行不会造成很大的危害,但我不确定这是最好的做法。如果我单独添加新组件会更好吗?还是说我正在做的事情不太遥远 代码,适用于更直观的人: public async Tas

我目前有一个对象
报告
。此报表对象有多个子实体,例如
WorkOrder
ReleaseQuestions
。我只是想问一下将
WorkOrder
ReleaseQuestions
添加到数据库中的最佳实践。当前,在创建报表时,我会将新的空白对象添加到报表对象中,然后将其添加到数据库中。这是因为最终这些组件将由用户填写,所以在数据库中放置空白行不会造成很大的危害,但我不确定这是最好的做法。如果我单独添加新组件会更好吗?还是说我正在做的事情不太遥远

代码,适用于更直观的人:

public async Task<ReportModel> AddReport(ReportModel reportModel)
{
    // CapacityPlanReport report = _mapper.Map<ReportModel, CapacityPlanReport>(reportModel);

    var report = new CapacityPlanReport
    {
        AddedYear = DateTime.Now.ToString(),
        Type = reportModel.Type,
        Eta = reportModel.Eta
    };

    // Create the corresponding pieces of the report in the database.
    report.ReleaseQuestion = new CapacityPlanReleaseQuestion();
    report.WorkOrder = new CapacityPlanWorkOrder();

    _context.CapacityPlanReport.Add(report);
    await _context.SaveChangesAsync();

    var result = await GetReport(report.CapacityPlanReportId);
    return result;
}
公共异步任务AddReport(ReportModel ReportModel) { //CapacityPlanReport=\u mapper.Map(reportModel); var报告=新容量计划报告 { AddedYear=DateTime.Now.ToString(), Type=reportModel.Type, Eta=报告模型。Eta }; //在数据库中创建报告的相应部分。 report.ReleaseQuestion=新容量PlanReleaseQuestion(); report.WorkOrder=新容量计划WorkOrder(); _context.CapacityPlanReport.Add(报告); wait_context.SaveChangesAsync(); var结果=等待GetReport(report.CapacityPlanReportId); 返回结果; }
如果用户稍后将填写组件,则仅在插入
报告时不填写组件,并使用
null
s。当用户向您提供适当的数据时,创建实体,将其分配给报告,然后
SaveChanges
-EF将更新现有的
报告
,并将子实体连同所有必要的FK引用一起插入数据库


对于还不存在的东西来说,将其设置为
null
可能比将其设置为空实例更为自然。空实例毕竟是一种东西。

你能提供你的实体对象吗?请解释你所说的
子实体是什么意思。如果您的意思是:
Employee
,然后是subentity
Manager
,那么您所做的是不正确的,因为每个员工都不是经理,所以永远不会填写。如何更好?如果代码起作用,它就起作用。否则,它只是对它应该如何工作的意见,而对堆栈溢出的意见实际上并不起作用。