简体   繁体   English

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

[英]Best Practice for Adding an Entity with Multiple Subentities (Entity Framework)

I currently have an object Report . 我目前有一个对象Report This report object has multiple subentities, such as WorkOrder and ReleaseQuestions . 此报告对象具有多个WorkOrder ,例如WorkOrderReleaseQuestions I just wanted to ask the best practice for adding WorkOrder 's and ReleaseQuestions 's to the database. 我只是想问一下将WorkOrderReleaseQuestions添加到数据库的最佳实践。 Currently, when a report is created, I add new blank objects to my report object, then add that to the database. 当前,当创建报告时,我将新的空白对象添加到我的报告对象中,然后将其添加到数据库中。 This is because eventually these components will be filled out by the user, so having the blank rows sitting in the database doesn't do much harm, but I'm not sure this is the best practice. 这是因为最终这些组件将由用户填写,因此将空白行放在数据库中并不会带来太大危害,但是我不确定这是最佳实践。 Would it be better if I added the new components separately? 如果单独添加新组件会更好吗? Or is what I'm doing not too far off? 还是我在做的事不太远?

Code, for people who are more visual: 代码,适用于更直观的人:

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

If the components are going to be filled out by the user later , then just don't fill them at all when inserting the Report only and use null s. 如果组件将由用户稍后填充,则仅在插入Report并使用null时根本不填充它们。 When the user provides you with appropriate data, create the entity, assign it to the report and SaveChanges - EF will update your existing Report and insert the subentity into the db along with all necessary FK references. 当用户为您提供适当的数据时,创建实体,将其分配给报表,然后保存更改SaveChanges将更新您现有的Report ,并将子实体与所有必要的FK引用一起插入数据库。

It's probably more natural for something that does not exist yet to be null rather than an empty instance. 它的东西,不存在尚待可能更自然null ,而不是一个空的实例。 An empty instance is something after all. 一个空的实例毕竟是东西

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM