在查询EF Core 2.1时从对象中删除某些属性 [英] Remove certain properties from object upon query EF Core 2.1
问题描述
我正在尝试将所有查询的IsoDataTables的ID完全清空或完全删除,然后再将其返回到前端。这个想法是(在这种情况下)它应该作为模板,并且我不希望它将ID返回给我,也不希望它们在前端被删除。
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.
推荐答案
我的方法是创建一个复制构造函数(或者基本上是一个复制构造函数)。具有所需字段的对象的新实例);我选择了一个复制构造函数,因为这种逻辑在其他地方也同样适用。另一个类似的解决方案是创建一个DTO对象,但是我在这里不需要它。是否有改善?
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);
这篇关于在查询EF Core 2.1时从对象中删除某些属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!