Sachin Singh
Sachin Singh

Reputation: 204

how to get Id of last added row when using entity framework with unit of work pattern

how to get Id of last added row when using entity framework with unit of work pattern?? I know after SaveChanges() the auto incremented column gets autometically updated you can get it as:-

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

(Easy Solution) but how to do the same when using unit of work??And please don't say why u need unit of work DbContext is already unit of work. Action in Controller

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");


                    }

Service Method

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

unit of work:-

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

            }

Upvotes: 1

Views: 1598

Answers (1)

Leonardo Henriques
Leonardo Henriques

Reputation: 782

Create a method on your CommentRepository that returns the last inserted comment:

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

Then when you are using your UnitOfWork just access it:

var comment = _uow.CommentRepository.ReturnLast();

I don't know how your repository is built, so I'm just guessing here. You should not use UnitOfWork inside of the repository.

Upvotes: 1

Related Questions