Remove certain properties from object upon query EF Core 2.1

c# ef-core-2.1 ef-fluent-api entity-framework entity-framework-core

Question

I'm trying to null or remove the ID entirely of all the queried IsoDataTables before returning them to frontend. The idea is that it should behave (in this case) as a template and I don't want it returning the id's back to me, nor do I want them to be removed in the frontend.

var applicationType = await _context.ApplicationType
                                    .Include(m => m.IsoTableData)
                                    .AsNoTracking()
                                    .FirstOrDefaultAsync(m => m.Id == id);

if (applicationType == null)
{
    return NotFound();
}

if (applicationType.IsoTableData != null)
{
    foreach (IsoTableData isoTableData in applicationType.IsoTableData)
    {
        // error since it a not nullable primary key
        isoTableData.Id = null;
    }
}

return Ok(applicationType);

I have found a workaround in which I duplicate the objects and return them (without saving to DB) but I'm looking for a more elegant solution.

1
0
9/29/2018 8:09:20 PM

Popular Answer

The way I did it was create a copy constructor (or basically, a new instance of an object) with the desired fields; I chose a copy constructor as this logic is recurent in other places as well. Another similar solution is creating a DTO object, but I don't need it here. Any improvements?

//in IsoFileApplicationType.cs
public IsoFileApplicationType(IsoFileApplicationType isoFileApplicationType)
{
    Id = null
    FullName = isoFileApplicationType.FullName;
    Name = isoFileApplicationType.Name;
    (...)


    foreach (IsoTableData isoTableData in isoFileApplicationType.IsoTableData)
    {
        IsoTableData.Add(IsoTableData(isoTableData));
    }
}

//in IsoTableData.cs
public IsoTableData(IsoTableData isoTableData)
{
    Id = null;
    Data = isoTableData.Name;
    Age = isoTableData.Age;
    (...)
}

// in CRUD controller
var applicationType = await _context.ApplicationType
                                   .Include(m => m.IsoTableData)
                                   .AsNoTracking()
                                   .FirstOrDefaultAsync(m => m.Id == id);

if (applicationType == null)
{
    return NotFound();
}
IsoFileApplicationType newIsoFileApplicationType = IsoFileApplicationType(applicationType);
return Ok(newIsoFileApplicationType);
0
9/30/2018 12:36:38 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