【问题标题】:Best Practice for Adding an Entity with Multiple Subentities (Entity Framework)添加具有多个子实体的实体的最佳实践(实体框架)
【发布时间】:2018-08-06 17:32:44
【问题描述】:

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

代码,适合更直观的人:

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;
}

【问题讨论】:

  • 你能提供你的实体对象吗?
  • 请解释subentities是什么意思。如果您的意思是:Employee,然后是子实体Manager,那么您所做的就是不正确的,因为每个员工都不是经理,所以它永远不会被填写。
  • 如何更好?如果代码有效,它就有效。否则,它只是关于它应该如何工作的意见,而意见并不真正适用于 Stack Overflow。

标签: c# asp.net entity-framework entity-framework-core


【解决方案1】:

如果组件将由用户稍后填写,那么在仅插入Report 时根本不填写它们并使用nulls。当用户为您提供适当的数据时,创建实体,将其分配给报告和 SaveChanges - EF 将更新您现有的 Report 并将子实体与所有必要的 FK 引用一起插入到数据库中。

对于尚不存在的东西来说,null 可能比空实例更自然。毕竟,一个空实例是什么

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-01
    • 2022-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-14
    • 2023-03-28
    相关资源
    最近更新 更多