如何在将实体框架与工作单元模式一起使用时获取上次添加的行的 ID



使用具有工作单元模式的实体框架时,如何获取最后添加的行的 ID? 我知道在保存更改((之后,自动递增的列会自动更新,您可以将其设置为:-

Comment comment=new comment();
comment.username="sachin";
db.saveChanges();
var id= comment.commentId;

(简单的解决方案(但是在使用工作单元时如何做同样的事情?请不要说为什么需要工作单元 DbContext 已经是工作单元了。 控制器中的操作

public ActionResult Savecomment(string comment)
{
var user = (from a in _registrationService.GetAllRegistrations() where a.Email == Convert.ToString(Session["Email"]) select a).FirstOrDefault();
var userid = Convert.ToInt32(user.UserId);
if (ModelState.IsValid)
{
Comment cmt = new Comment();
cmt.CommentId = cmt.CommentId;
cmt.DateTime = System.DateTime.Now;
cmt.PostId = Convert.ToInt32(TempData["pid"]);
cmt.UserId = userid;
cmt.Body = comment;
_commentService.CreateComment(cmt);
var id=cmt.CommentId;//I need this
var res = _commentService.GetCommentById(id);
return Json(res,JsonRequestBehavior.AllowGet);
}
return RedirectToAction("Index","Home");

}

服务方式

public Comment CreateComment(Comment CommentEntity)
{
using (var scope = new TransactionScope())
{
var Comment = new Comment
{
CommentId=CommentEntity.CommentId,
Body = CommentEntity.Body,
UserId = CommentEntity.UserId,
DateTime = CommentEntity.DateTime,
PostId=CommentEntity.PostId,
};
_unitOfWork.CommentRepository.Insert(Comment);
_unitOfWork.Save();
scope.Complete();
return Comment;
}
}

工作单位:-

public Repository<Comment> CommentRepository
{
get
{
if (this._CommentRepository == null)
this._CommentRepository = new Repository<Comment>(_context);
return _CommentRepository;
}
}
public void Save()
{
try
{
_context.SaveChanges();
}
catch (DbEntityValidationException e)
{
var outputLines = new List<string>();
foreach (var eve in e.EntityValidationErrors)
{
outputLines.Add(string.Format("{0}: Entity of type "{1}" in state "{2}" has the following validation errors:", DateTime.Now, eve.Entry.Entity.GetType().Name, eve.Entry.State));
foreach (var ve in eve.ValidationErrors)
{
outputLines.Add(string.Format("- Property: "{0}", Error: "{1}"", ve.PropertyName, ve.ErrorMessage));
}
}
//System.IO.File.AppendAllLines(@"C:errors.txt", outputLines);
throw e;
}
}

CommentRepository上创建一个返回上次插入注释的方法:

public class CommentRepository: ICommentRepository //Only if you have the interface
{   
internal DbContext _context;
internal DbSet<Comment> dbSet;
public CommentRepository(DbContext context)//I think you have something like this.
{
_context = context;
dbSet = context.Set<Comment>();
}
(...)
public int ReturnLast()
{
//Use your context or DbSet here to return the data.
//You are using .Last() but I'm not sure if that gets what you want.
var lastComment = dbSet.ToList().Last();
return lastComment.Id;
}
}

然后,当您使用工作单元时,只需访问它:

var comment = _uow.CommentRepository.ReturnLast();

我不知道你的存储库是如何构建的,所以我只是在这里猜测。不应在存储库中使用 UnitOfWork。

最新更新