当使用具有工作单元模式的实体框架时,如何获得最后添加行的Id

时间:2018-05-11 11:01:03

标签: c# entity-framework unit-of-work

当使用具有工作单元模式的实体框架时,如何获取最后添加的行的ID? 我知道在SaveChanges()之后,自动增量列会自动更新,你可以得到它: -

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;
                }

            }

0 个答案:

没有答案