我尝试将IEnumerable添加到我的数据库中,然后在保存更改后获取其密钥(id)。 如果我只添加一个实体(没有集合),则在SaveChanges()之后自动填充id,但是在集合中 - 这不起作用。
以下是存储库中的Add(OrUpdate)方法:
private void Add(IEnumerable<LabLineEntity> p_lines)
{
foreach (var line in p_lines)
{
line.isActive = true;
}
//assume this gets a main-work from the context, all line are related to a specific work
LabMainEntity labMain = GetSpecific<LabMainEntity>(p_lines.First().AssignedToWork);
m_context.LabLines.AddRange(p_lines);
foreach (var line in p_lines) // adds to the ICollection
{
labMain.Lines.Add(line);
}
}
public void AddOrUpdate(IEnumerable<LabLineEntity> p_labLines)
{
if (!LinesAreLegal(p_labLines))
{
throw new Exception("Lab lines are not legal!");
}
var newLabLines = p_labLines.Where(l => l.Id == Guid.Empty);
var existingLabLines = p_labLines.Where(l => l.Id != Guid.Empty);
LabMainEntity labMain = GetSpecific<LabMainEntity>(p_labLines.First().AssignedToWork);
if (existingLabLines.Any())
{
HashSet<Guid> existingLineIds = new HashSet<Guid>(existingLabLines.Select(l => l.Id));
// from all the lines in the main, select those that are NOT in the lines to update.
// this will return the lines that should be removed!
HashSet<Guid> linesToRemove = new HashSet<Guid>(labMain.Lines.Where(ell => !existingLineIds.Contains(ell.Id)).Select(t=>t.Id));
foreach (var lineGuid in linesToRemove)
{
LabLineEntity lineInDb = GetSpecific<LabLineEntity>(lineGuid);
m_context.LabLines.Remove(lineInDb);
labMain.Lines.Remove(lineInDb);
}
Update(existingLabLines);
}
if (newLabLines.Any())
{
Add(newLabLines);
}
}
这是外线电话:
[HttpPost("")]
public async Task<IActionResult> AddOrUpdateLabLine([FromBody] IEnumerable<LabLineEntityViewModel> p_labLinesVM)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState.ToString());
}
IEnumerable<LabLineEntity> labLinesE = m_mapper.ViewModelToModel(p_labLinesVM);
try
{
m_repository.AddOrUpdate(labLinesE);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
if (!(await m_repository.SaveChangesAsync()))
{
return BadRequest("Failed to save to the Database (ModelState was ok)");
}
List<LabLineEntity> labLinesToReturn = new List<LabLineEntity>();
foreach (var labLine in labLinesE)
{
//THIS IS NULL :(
LabLineEntity lineToAdd = m_repository.GetSpecific<LabLineEntity>(labLine.Id);
labLinesToReturn.Add(lineToAdd);
}
IEnumerable<LabLineEntityViewModel> returnedValue = m_mapper.ModelToViewModel(labLinesToReturn);
return Created($"Modules/Lab/Forms/Main/", returnedValue);
}
SaveChanges:
public async Task<bool> SaveChangesAsync()
{
int rowsChanged = 0;
try
{
rowsChanged = await m_context.SaveChangesAsync();
}
catch (Exception)
{
// ignored
}
return rowsChanged > 0;
}
在此方法之后,从外部函数(传递集合)调用SaveChanges(Async),但不填充ID。
任何解决方案? 此致