【发布时间】:2022-02-03 04:01:01
【问题描述】:
我有一个 DTO:
public class UserDTO
{
public int uid {get;set;}
public string name {get;set;}
}
// example of what the udto gets as a request from the front-end
var theList = new List<UserDTO>()
{
new UserDTO { uid = 1, name = "Bob Smith" },
new UserDTO { uid = 2, name = "Jane Jones" },
};
在数据库中:Bob 的存在状态为 0,而 Janes 不存在于数据库中。因此循环检查用户是否存在状态为 0,如果存在,则使用 _myCtx.Update() 将 DB 状态从 0 更新为 1。然后一旦更新,它会删除 Bob 的对象,因为我不想复制 Bob,因为他已经存在,我需要删除 Bobs 对象,然后继续下一个循环,将 Jane 添加到数据库中。
public async Task<IActionResult> AddUser([FromBody] List<UserDTO> udto)
{
var toRemove = new HashSet<UserDTO>();
foreach(var item in udto)
{
var userFalse = await _myCtx.Users.SingleOrDefaultAsync(o => o.uid == item.uid && o.status == 0);
if(userFalse != null) // if user found, I want to update
{
item.Status = 1;
_myCtx.Users.Update(userFalse);
await _myCtx.SaveChanges(); //save into the DB the status to 1
if(item.uid == userFalse.uid){ toRemove.Add(item); } //need Bob removed here
} // below I want to add if they don't exist
udto.RemoveAll(toRemove.Contains);
item.name = udto.name;
var myEntity = _mapper.Map(item);
await _myCtx.Users.AddAsync(myEntity);
// Jane gets added, but so does Bob as a duplicate
}
await _myCtx.SaveChangesAsync();
return Ok("User Added");
}
循环完成后删除该项目以及将其添加到数据库的原因。有没有办法在 if 子句之后或内部继续之前删除 Bob,这样它就不会被添加到数据库中?谢谢大家。
【问题讨论】:
-
@Selvin 好吧,你没用 - 如果它被问了很多次,你应该提供一个链接,而不仅仅是投反对票......我已经找到了这个(stackoverflow.com/questions/853526/…),但不起作用就我而言(因为我确实搜索过)
-
请创建一个Minimum Reproducible Example。我们不知道
_myCtx是什么。而所有async的废话会使您的代码难以理解,并可能导致您出现问题 -
我已经欺骗了你的问题,因为我相信它是重复的 - 但如果不是,那么请更新你的问题(使其与链接的问题完全不同),它可能是重新打开。
-
@slugster 这很相似,但在循环内有一个更新和插入任务到数据库中,您提供的链接是重复的,我还添加了它作为上面对 Selvin 的引用,但这并没有完全回答我的问题。
标签: c# api entity-framework .net-core