locked
How customize CRUD with user and datetime data in generic repository unit of work pattern in asp.net. RRS feed

  • Question

  • User1984354752 posted

    Hi there:

    I successfully implemented a generic repository unit of work pattern in ASP.NET core.  My issue is that I want to post to the database when I edit or insert the Id of the user who modify/insert the records together with the date and don't know how to do it in the best efficient way. I attached below how the controller call the edit action .

    My understanding  is that  the class repository is the place where I must encapsulate all the Business logic hence I assume that is there where I have to pass the values. I have extensively searched in the internet but I haven't find a simple example addressing this issue. I just only need an example or reference to start with. 

    Controller: 

    public string Edit(Contract Model)
    {
    string msg;

    try
    {
    if (ModelState.IsValid)
    {
    db.Contractrepository.Update(Model);
    db.Save();
    msg = "Saved Successfully";
    }
    else
    {
    var errors = ModelState.Values.SelectMany(v => v.Errors);
    msg = errors.ToString();

    }
    }
    catch (Exception ex)
    {
    msg = "Error occured:" + ex.Message;
    }
    return msg;

    }

    Thursday, July 2, 2020 9:04 PM

Answers

  • User1686398519 posted

    Hi 9peculiar,

    I made an example according to your needs, please refer to it.

    • I give this example to illustrate how to save the date and user ID of adding a new product. This method is also suitable for editing and other operations.

    Model

        public class User
        {
            [Key]
            public int id { get; set; }
            public string name { get; set; }
            public string password { get; set; }
        }
        public class Product
        {
            [Key]
            public int id { get; set; }
            public string name { get; set; }
            public int uploaderId { get; set; }
            [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd hh:mm:ss}", ApplyFormatInEditMode = true)]
            public string datetime { get; set; }
        }

    IRespository

        public interface IUserRespository : IDisposable
        {
            User login(User user);
            void add(User user);
            void Save();
        }
        public interface IProductRepository : IDisposable
        {
            IEnumerable<Product> GetProducts();
            void InsertProduct(Product product, int id, string time);
            void Save();
        }

    Respository

        public class UserRespository : IUserRespository, IDisposable
        {
            private ModelContext context;
    
            public UserRespository(ModelContext context)
            {
                this.context = context;
            }
            public User login(User user)
            {
                var existUser = context.Users.Where(u => u.name == user.name && u.password == user.password).SingleOrDefault();
                if (existUser != null)
                {
                    return existUser;
                }
                else
                {
                    return null;
                }
            }
            public void Save()
            {
                context.SaveChanges();
            }
    
            private bool disposed = false;
    
            protected virtual void Dispose(bool disposing)
            {
                if (!this.disposed)
                {
                    if (disposing)
                    {
                        context.Dispose();
                    }
                }
                this.disposed = true;
            }
            public void Dispose()
            {
                Dispose(true);
                GC.SuppressFinalize(this);
            }
            public void add(User user)
            {
                context.Users.Add(user);
            }
        }
        public class ProductRepository : IProductRepository, IDisposable
        {
            private ModelContext context;
            public ProductRepository(ModelContext context)
            {
                this.context = context;
            }
            public IEnumerable<Product> GetProducts()
            {
                return context.Products.ToList();
            }
    
            public void InsertProduct(Product product, int id, string time)
            {
                product.uploaderId = id;
                product.datetime = time;
                context.Products.Add(product);
            }
    
            public void Save()
            {
                context.SaveChanges();
            }
            private bool disposed = false;
            protected virtual void Dispose(bool disposing)
            {
                if (!this.disposed)
                {
                    if (disposing)
                    {
                        context.Dispose();
                    }
                }
                this.disposed = true;
            }
            public void Dispose()
            {
                Dispose(true);
                GC.SuppressFinalize(this);
            }
        }

    ProductController

            private IProductRepository productRepository;
    
            public ProductController(IProductRepository _productRepository)
            {
                productRepository = _productRepository;
            }
            public IActionResult Index()
            {
    
                return View(productRepository.GetProducts());
            }
            public IActionResult Create()
            {
                return View();
            }
            [HttpPost]
            [ValidateAntiForgeryToken]
            public IActionResult Create(Product product)
            {
                int upId = int.Parse(HttpContext.Session.GetString("userId"));
                string time = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                productRepository.InsertProduct(product, upId, time);
                productRepository.Save();
                return RedirectToAction("Index","Product",product);
            }

    UserController

            private IUserRespository userRespository;
            public UserController(IUserRespository _userRespository)
            {
                userRespository= _userRespository;
            }
            public IActionResult Login()
            {
                return View();
            }
            [HttpPost]
            public IActionResult Login(User user)
            {
                var result = userRespository.login(user);
                if (result != null)
                {
                    HttpContext.Session.SetString("userId", result.id.ToString());
                    HttpContext.Session.SetString("username",result.name.ToString());
                    return RedirectToAction("Index", "Product");
                }
                else
                {
                    return View();
                }
            }
            public IActionResult Logout()
            {
                HttpContext.Session.Clear();
                return RedirectToAction("Login", "User"); ;
            }

    Login

    @model WebApplication7.Models.User
    @using (Html.BeginForm("Login", "User", FormMethod.Post))
    {
        <div class="container">
            <div class="row clearfix">
                <div class="col-md-12 column">
                    <form class="form-horizontal" role="form">
                        <div class="form-group">
                            @Html.LabelFor(model => model.name, htmlAttributes: new { @class = "control-label col-md-2" })
                            <div class="col-md-10">
                                @Html.EditorFor(model => model.name, new { htmlAttributes = new { @class = "form-control" } })
                                @Html.ValidationMessageFor(model => model.name, "", new { @class = "text-danger" })
                            </div>
                        </div>
                        <br /><br />
                        <div class="form-group">
                            @Html.LabelFor(model => model.password, htmlAttributes: new { @class = "control-label col-md-2" })
                            <div class="col-md-10">
                                @Html.EditorFor(model => model.password, new { htmlAttributes = new { @class = "form-control" } })
                                @Html.ValidationMessageFor(model => model.password, "", new { @class = "text-danger" })
                            </div>
                        </div>
                        <br /><br />
                        <br />
                        <div class="form-group">
                            <div class="col-sm-offset-2 col-sm-10">
                                <button type="submit" class="btn btn-default">Login</button>&nbsp;
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    }
    

    Index

    @model IEnumerable<WebApplication7.Models.Product>
    <p>
        @Html.ActionLink("Create New", "Create")
    </p>
    <table class="table">
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.name)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.uploaderId)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.datetime)
            </th>
            <th></th>
        </tr>
        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.name)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.uploaderId)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.datetime)
                </td>
            </tr>
        }
    </table>
    @Html.ActionLink("LogOut","LogOut","User")
    

    Create

    @model WebApplication7.Models.Product
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
        <div class="form-horizontal">
            <h4>Product</h4>
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(model => model.name, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.name, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.name, "", new { @class = "text-danger" })
                </div>
            </div>
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Create" class="btn btn-default" />
                </div>
            </div>
        </div>
    }
    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>
    

    Here is the result.

    Best Regards,

    YihuiSun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, July 3, 2020 9:28 AM
  • User1984354752 posted

    Dear YihuiSun:

    Thanks a million this is what I was looking for !!!!!....Have a nice day further smile

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, July 3, 2020 9:37 AM

All replies

  • User475983607 posted

    Typically, your generic repository design has a property for the userId and the datetime pertaining to the record you are trying to save.   We cannot see your design and have no idea why you are unable to pass this information.  Usually, the user id or username comes form your security which we also cannot see.

    Thursday, July 2, 2020 11:08 PM
  • User1686398519 posted

    Hi 9peculiar,

    I made an example according to your needs, please refer to it.

    • I give this example to illustrate how to save the date and user ID of adding a new product. This method is also suitable for editing and other operations.

    Model

        public class User
        {
            [Key]
            public int id { get; set; }
            public string name { get; set; }
            public string password { get; set; }
        }
        public class Product
        {
            [Key]
            public int id { get; set; }
            public string name { get; set; }
            public int uploaderId { get; set; }
            [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd hh:mm:ss}", ApplyFormatInEditMode = true)]
            public string datetime { get; set; }
        }

    IRespository

        public interface IUserRespository : IDisposable
        {
            User login(User user);
            void add(User user);
            void Save();
        }
        public interface IProductRepository : IDisposable
        {
            IEnumerable<Product> GetProducts();
            void InsertProduct(Product product, int id, string time);
            void Save();
        }

    Respository

        public class UserRespository : IUserRespository, IDisposable
        {
            private ModelContext context;
    
            public UserRespository(ModelContext context)
            {
                this.context = context;
            }
            public User login(User user)
            {
                var existUser = context.Users.Where(u => u.name == user.name && u.password == user.password).SingleOrDefault();
                if (existUser != null)
                {
                    return existUser;
                }
                else
                {
                    return null;
                }
            }
            public void Save()
            {
                context.SaveChanges();
            }
    
            private bool disposed = false;
    
            protected virtual void Dispose(bool disposing)
            {
                if (!this.disposed)
                {
                    if (disposing)
                    {
                        context.Dispose();
                    }
                }
                this.disposed = true;
            }
            public void Dispose()
            {
                Dispose(true);
                GC.SuppressFinalize(this);
            }
            public void add(User user)
            {
                context.Users.Add(user);
            }
        }
        public class ProductRepository : IProductRepository, IDisposable
        {
            private ModelContext context;
            public ProductRepository(ModelContext context)
            {
                this.context = context;
            }
            public IEnumerable<Product> GetProducts()
            {
                return context.Products.ToList();
            }
    
            public void InsertProduct(Product product, int id, string time)
            {
                product.uploaderId = id;
                product.datetime = time;
                context.Products.Add(product);
            }
    
            public void Save()
            {
                context.SaveChanges();
            }
            private bool disposed = false;
            protected virtual void Dispose(bool disposing)
            {
                if (!this.disposed)
                {
                    if (disposing)
                    {
                        context.Dispose();
                    }
                }
                this.disposed = true;
            }
            public void Dispose()
            {
                Dispose(true);
                GC.SuppressFinalize(this);
            }
        }

    ProductController

            private IProductRepository productRepository;
    
            public ProductController(IProductRepository _productRepository)
            {
                productRepository = _productRepository;
            }
            public IActionResult Index()
            {
    
                return View(productRepository.GetProducts());
            }
            public IActionResult Create()
            {
                return View();
            }
            [HttpPost]
            [ValidateAntiForgeryToken]
            public IActionResult Create(Product product)
            {
                int upId = int.Parse(HttpContext.Session.GetString("userId"));
                string time = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                productRepository.InsertProduct(product, upId, time);
                productRepository.Save();
                return RedirectToAction("Index","Product",product);
            }

    UserController

            private IUserRespository userRespository;
            public UserController(IUserRespository _userRespository)
            {
                userRespository= _userRespository;
            }
            public IActionResult Login()
            {
                return View();
            }
            [HttpPost]
            public IActionResult Login(User user)
            {
                var result = userRespository.login(user);
                if (result != null)
                {
                    HttpContext.Session.SetString("userId", result.id.ToString());
                    HttpContext.Session.SetString("username",result.name.ToString());
                    return RedirectToAction("Index", "Product");
                }
                else
                {
                    return View();
                }
            }
            public IActionResult Logout()
            {
                HttpContext.Session.Clear();
                return RedirectToAction("Login", "User"); ;
            }

    Login

    @model WebApplication7.Models.User
    @using (Html.BeginForm("Login", "User", FormMethod.Post))
    {
        <div class="container">
            <div class="row clearfix">
                <div class="col-md-12 column">
                    <form class="form-horizontal" role="form">
                        <div class="form-group">
                            @Html.LabelFor(model => model.name, htmlAttributes: new { @class = "control-label col-md-2" })
                            <div class="col-md-10">
                                @Html.EditorFor(model => model.name, new { htmlAttributes = new { @class = "form-control" } })
                                @Html.ValidationMessageFor(model => model.name, "", new { @class = "text-danger" })
                            </div>
                        </div>
                        <br /><br />
                        <div class="form-group">
                            @Html.LabelFor(model => model.password, htmlAttributes: new { @class = "control-label col-md-2" })
                            <div class="col-md-10">
                                @Html.EditorFor(model => model.password, new { htmlAttributes = new { @class = "form-control" } })
                                @Html.ValidationMessageFor(model => model.password, "", new { @class = "text-danger" })
                            </div>
                        </div>
                        <br /><br />
                        <br />
                        <div class="form-group">
                            <div class="col-sm-offset-2 col-sm-10">
                                <button type="submit" class="btn btn-default">Login</button>&nbsp;
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    }
    

    Index

    @model IEnumerable<WebApplication7.Models.Product>
    <p>
        @Html.ActionLink("Create New", "Create")
    </p>
    <table class="table">
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.name)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.uploaderId)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.datetime)
            </th>
            <th></th>
        </tr>
        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.name)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.uploaderId)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.datetime)
                </td>
            </tr>
        }
    </table>
    @Html.ActionLink("LogOut","LogOut","User")
    

    Create

    @model WebApplication7.Models.Product
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
        <div class="form-horizontal">
            <h4>Product</h4>
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(model => model.name, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.name, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.name, "", new { @class = "text-danger" })
                </div>
            </div>
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Create" class="btn btn-default" />
                </div>
            </div>
        </div>
    }
    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>
    

    Here is the result.

    Best Regards,

    YihuiSun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, July 3, 2020 9:28 AM
  • User1984354752 posted

    Dear YihuiSun:

    Thanks a million this is what I was looking for !!!!!....Have a nice day further smile

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, July 3, 2020 9:37 AM