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

asp.net c# entity-framework entity-framework-core

Question

I currently have an object Report. This report object has multiple subentities, such as WorkOrder and ReleaseQuestions. I just wanted to ask the best practice for adding WorkOrder's and ReleaseQuestions's to the database. 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;
}
1
0
8/6/2018 5:32:44 PM

Popular Answer

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 nulls. 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.

It's probably more natural for something that does not exist yet to be null rather than an empty instance. An empty instance is something after all.

0
8/6/2018 7:45:13 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow