ASP.NET中使用EF根据UserID和errandID返回提交的DB记录问题
解决ASP.NET EF提交后无法获取刚提交记录的问题
Hey there! Let's work through this problem together—you've got the data saving part working, which is a huge win, so let's get that returned record sorted out.
方法1:直接使用SaveChanges()后的实体(最省心)
Entity Framework automatically updates your entity object with database-generated values (like auto-incrementing ErrandID) right after you call SaveChanges(). That means you don't even need to query the database again—you already have the full record in memory.
Here's how that looks in code:
// 假设你的实体类是 Errand var newErrand = new Errand { UserID = currentUserID, // 你从登录用户获取的UserID // 给其他字段赋值(比如标题、描述等) }; // 添加到上下文并保存 _dbContext.Errands.Add(newErrand); _dbContext.SaveChanges(); // 执行后,newErrand.ErrandID会被EF自动填充 // 直接返回这个实体就行!它就是刚提交到数据库的完整记录 return newErrand;
方法2:如果必须查询(比如ErrandID是自定义生成的)
If you're manually setting ErrandID instead of letting the database auto-generate it, you can query using the UserID + ErrandID combo. Just make sure you avoid these common pitfalls:
- Always call SaveChanges() first: EF doesn't write to the database until you run this method—querying before will only check in-memory data (which might not match the database yet).
- Match parameter types exactly: Double-check that
UserID(string/int?) andErrandIDmatch the data types in your database and entity class. A type mismatch will silently fail to find the record. - Use async correctly if you're going async: Don't skip
awaitonSaveChangesAsync()or your query might run before the save finishes.
Example query code:
// 先提交数据 var newErrand = new Errand { UserID = currentUserID, ErrandID = yourCustomGeneratedID, // 自定义的ErrandID // 其他字段 }; _dbContext.Errands.Add(newErrand); _dbContext.SaveChanges(); // 同步写法 // 或者异步写法(推荐) // await _dbContext.Errands.AddAsync(newErrand); // await _dbContext.SaveChangesAsync(); // 查询刚提交的记录 var submittedErrand = _dbContext.Errands .FirstOrDefault(e => e.UserID == currentUserID && e.ErrandID == newErrand.ErrandID); if (submittedErrand != null) { // 成功获取记录,继续你的逻辑 } else { // 没找到?检查这几点: // 1. UserID和ErrandID的值是否和提交的完全一致 // 2. SaveChanges()有没有抛出异常(可能保存失败了但你没捕获) // 3. 数据库里是否真的有这条记录(直接查数据库验证) }
常见排查点如果还是找不到
- Check transactions: If you're using a manual transaction, make sure it's committed before querying. EF's default behavior commits after
SaveChanges(), but custom transactions might delay this. - Verify entity mappings: Ensure your
Errandclass properties (UserID,ErrandID) are correctly mapped to the database columns (no typos, case mismatches, or missing mappings). - Check for filters: If you've added global query filters to your DbContext (like soft delete filters), make sure your new record doesn't get excluded accidentally.
内容的提问来源于stack exchange,提问作者Ken-F
相关产品推荐
相关产品推荐

