Remove certain properties from object upon query EF Core 2.1

旧时模样 提交于 2019-12-13 03:39:52

问题


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:


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


来源:https://stackoverflow.com/questions/52571232/remove-certain-properties-from-object-upon-query-ef-core-2-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!