using System; namespace EF.Core { public abstract class BaseEntity { public Int64 ID { get; set; } public DateTime AddedDate { get; set; } public DateTime ModifiedDate { get; set; } public string IP { get; set; } } }
using System; namespace EF.Core.Data { public class Book : BaseEntity { public string Title { get; set; } public string Author { get; set; } public string ISBN { get; set; } public DateTime Published { get; set; } } }
using System; using System.Data.Entity; using System.Data.Entity.ModelConfiguration; using System.Linq; using System.Reflection; using EF.Core; namespace EF.Data { public class EFDbContext : DbContext { public EFDbContext() : base("name=DbConnectionString") { } public new IDbSet<TEntity> Set<TEntity>() where TEntity : BaseEntity { return base.Set<TEntity>(); } protected override void OnModelCreating(DbModelBuilder modelBuilder) { var typesToRegister = Assembly.GetExecutingAssembly().GetTypes() .Where(type => !String.IsNullOrEmpty(type.Namespace)) .Where(type => type.BaseType != null && type.BaseType.IsGenericType && type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>)); foreach (var type in typesToRegister) { dynamic configurationInstance = Activator.CreateInstance(type); modelBuilder.Configurations.Add(configurationInstance); } base.OnModelCreating(modelBuilder); } } }
using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.ModelConfiguration; using EF.Core.Data; namespace EF.Data.Mapping { public class BookMap : EntityTypeConfiguration<Book> { public BookMap() { HasKey(t => t.ID); Property(t => t.ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); Property(t => t.Title).IsRequired(); Property(t => t.Author).IsRequired(); Property(t => t.ISBN).IsRequired(); Property(t => t.Published).IsRequired(); ToTable("Books"); } } }
using System; using System.Data.Entity; using System.Data.Entity.Validation; using System.Linq; using EF.Core; namespace EF.Data { public class Repository<T> where T : BaseEntity { private readonly EFDbContext context; private IDbSet<T> entities; string errorMessage = string.Empty; public Repository(EFDbContext context) { this.context = context; } public T GetById(object id) { return this.Entities.Find(id); } public void Insert(T entity) { try { if (entity == null) { throw new ArgumentNullException("entity"); } this.Entities.Add(entity); this.context.SaveChanges(); } catch (DbEntityValidationException dbEx) { foreach (var validationErrors in dbEx.EntityValidationErrors) { foreach (var validationError in validationErrors.ValidationErrors) { errorMessage += string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage) + Environment.NewLine; } } throw new Exception(errorMessage, dbEx); } } public void Update(T entity) { try { if (entity == null) { throw new ArgumentNullException("entity"); } this.context.SaveChanges(); } catch (DbEntityValidationException dbEx) { foreach (var validationErrors in dbEx.EntityValidationErrors) { foreach (var validationError in validationErrors.ValidationErrors) { errorMessage += Environment.NewLine + string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage); } } throw new Exception(errorMessage, dbEx); } } public void Delete(T entity) { try { if (entity == null) { throw new ArgumentNullException("entity"); } this.Entities.Remove(entity); this.context.SaveChanges(); } catch (DbEntityValidationException dbEx) { foreach (var validationErrors in dbEx.EntityValidationErrors) { foreach (var validationError in validationErrors.ValidationErrors) { errorMessage += Environment.NewLine + string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage); } } throw new Exception(errorMessage, dbEx); } } public virtual IQueryable<T> Table { get { return this.Entities; } } private IDbSet<t> Entities { get { if (entities == null) { entities = context.Set<t>(); } return entities; } } } }
using System; using System.Collections.Generic; using EF.Core; namespace EF.Data { public class UnitOfWork : IDisposable { private readonly EFDbContext context; private bool disposed; private Dictionary<string,object> repositories; public UnitOfWork(EFDbContext context) { this.context = context; } public UnitOfWork() { context = new EFDbContext(); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } public void Save() { context.SaveChanges(); } public virtual void Dispose(bool disposing) { if (!disposed) { if (disposing) { context.Dispose(); } } disposed = true; } public Repository<T> Repository<T>() where T : BaseEntity { if (repositories == null) { repositories = new Dictionary<string,object>(); } var type = typeof(T).Name; if (!repositories.ContainsKey(type)) { var repositoryType = typeof(Repository<>); var repositoryInstance = Activator.CreateInstance(repositoryType.MakeGenericType(typeof(T)), context); repositories.Add(type, repositoryInstance); } return (Repository<t>)repositories[type]; } } }
using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using EF.Core.Data; using EF.Data; namespace EF.Web.Controllers { public class BookController : Controller { private UnitOfWork unitOfWork = new UnitOfWork(); private Repository<book> bookRepository; public BookController() { bookRepository = unitOfWork.Repository<book>(); } public ActionResult Index() { IEnumerable<book> books = bookRepository.Table.ToList(); return View(books); } public ActionResult CreateEditBook(int? id) { Book model = new Book(); if (id.HasValue) { model = bookRepository.GetById(id.Value); } return View(model); } [HttpPost] public ActionResult CreateEditBook(Book model) { if (model.ID == 0) { model.ModifiedDate = System.DateTime.Now; model.AddedDate = System.DateTime.Now; model.IP = Request.UserHostAddress; bookRepository.Insert(model); } else { var editModel = bookRepository.GetById(model.ID); editModel.Title = model.Title; editModel.Author = model.Author; editModel.ISBN = model.ISBN; editModel.Published = model.Published; editModel.ModifiedDate = System.DateTime.Now; editModel.IP = Request.UserHostAddress; bookRepository.Update(editModel); } if (model.ID > 0) { return RedirectToAction("Index"); } return View(model); } public ActionResult DeleteBook(int id) { Book model = bookRepository.GetById(id); return View(model); } [HttpPost,ActionName("DeleteBook")] public ActionResult ConfirmDeleteBook(int id) { Book model = bookRepository.GetById(id); bookRepository.Delete(model); return RedirectToAction("Index"); } public ActionResult DetailBook(int id) { Book model = bookRepository.GetById(id); return View(model); } protected override void Dispose(bool disposing) { unitOfWork.Dispose(); base.Dispose(disposing); } } }
(function ($) { function Book() { var $thisthis = this; function initializeAddEditBook() { $('.datepicker').datepicker({ "setDate": new Date(), "autoclose": true }); } $this.init = function () { initializeAddEditBook(); } } $(function () { var self = new Book(); self.init(); }); }(jQuery))
@model EF.Core.Data.Book @{ ViewBag.Title = "Create Edit Book"; } <div class="book-example panel panel-primary"> <div class="panel-heading panel-head">Add / Edit Book</div> <div class="panel-body"> @using (Html.BeginForm()) { <div class="form-horizontal"> <div class="form-group"> @Html.LabelFor(model => model.Title, new { @class = "col-lg-1 control-label" }) <div class="col-lg-9"> @Html.TextBoxFor(model => model.Title, new { @class = "form-control" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.ISBN, new { @class = "col-lg-1 control-label" }) <div class="col-lg-9"> @Html.TextBoxFor(model => model.ISBN, new { @class = "form-control" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.Author, new { @class = "col-lg-1 control-label" }) <div class="col-lg-9"> @Html.TextBoxFor(model => model.Author, new { @class = "form-control" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.Published, new { @class = "col-lg-1 control-label" }) <div class="col-lg-9"> @Html.TextBoxFor(model => model.Published, new { @class = "form-control datepicker" }) </div> </div> <div class="form-group"> <div class="col-lg-8"></div> <div class="col-lg-3"> @Html.ActionLink("Back to List", "Index", null, new { @class = "btn btn-default" }) <button class="btn btn-success" id="btnSubmit" type="submit"> Submit </button> </div> </div> </div> } </div> </div> @section scripts { <script src="~/Scripts/bootstrap-datepicker.js" type="text/javascript"></script> <script src="~/Scripts/book-create-edit.js" type="text/javascript"></script> }
@model IEnumerable<EF.Core.Data.Book> @using EF.Web.Models <div class="book-example panel panel-primary"> <div class="panel-heading panel-head">Books Listing</div> <div class="panel-body"> <a id="createEditBookModal" href="@Url.Action("CreateEditBook")" class="btn btn-success"> <span class="glyphicon glyphicon-plus"></span>Book </a> <table class="table" style="margin: 4px"> <tr> <th> @Html.DisplayNameFor(model => model.Title) </th> <th> @Html.DisplayNameFor(model => model.Author) </th> <th> @Html.DisplayNameFor(model => model.ISBN) </th> <th>Action </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.Title) </td> <td> @Html.DisplayFor(modelItem => item.Author) </td> <td> @Html.DisplayFor(modelItem => item.ISBN) </td> <td> @Html.ActionLink("Edit", "CreateEditBook", new { id = item.ID }, new { @class = "btn btn-success" }) | @Html.ActionLink("Details", "DetailBook", new { id = item.ID }, new { @class = "btn btn-primary" }) | @Html.ActionLink("Delete", "DeleteBook", new { id = item.ID }, new { @class = "btn btn-danger" }) </td> </tr> } </table> </div> </div>
@model EF.Core.Data.Book @{ ViewBag.Title = "Detail Book"; } <div class="book-example panel panel-primary"> <div class="panel-heading panel-head">Book Detail</div> <div class="panel-body"> <div class="form-horizontal"> <div class="form-group"> @Html.LabelFor(model => model.Title, new { @class = "col-lg-1 control-label" }) <div class="col-lg-9"> @Html.DisplayFor(model => model.Title, new { @class = "form-control" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.Author, new { @class = "col-lg-1 control-label" }) <div class="col-lg-9"> @Html.DisplayFor(model => model.Author, new { @class = "form-control" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.ISBN, new { @class = "col-lg-1 control-label" }) <div class="col-lg-9"> @Html.DisplayFor(model => model.ISBN, new { @class = "form-control" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.Published, new { @class = "col-lg-1 control-label" }) <div class="col-lg-9"> @Html.DisplayFor(model => model.Published, new { @class = "form-control" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.AddedDate, new { @class = "col-lg-1 control-label" }) <div class="col-lg-9"> @Html.DisplayFor(model => model.AddedDate, new { @class = "form-control" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.ModifiedDate, new { @class = "col-lg-1 control-label" }) <div class="col-lg-9"> @Html.DisplayFor(model => model.ModifiedDate, new { @class = "form-control" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.IP, new { @class = "col-lg-1 control-label" }) <div class="col-lg-9"> @Html.DisplayFor(model => model.IP, new { @class = "form-control" }) </div> </div> @using (Html.BeginForm()) { <div class="form-group"> <div class="col-lg-1"></div> <div class="col-lg-9"> @Html.ActionLink("Edit", "CreateEditBook", new { id = Model.ID }, new { @class = "btn btn-primary" }) @Html.ActionLink("Back to List", "Index", null, new { @class = "btn btn-success" }) </div> </div> } </div> </div> </div>
@model EF.Core.Data.Book @{ ViewBag.Title = "Delete Book"; } <div class="book-example panel panel-primary"> <div class="panel-heading panel-head">Delete Book</div> <div class="panel-body"> <h3>Are you sure you want to delete this?</h3> <h1>@ViewBag.ErrorMessage</h1> <div class="form-horizontal"> <div class="form-group"> @Html.LabelFor(model => model.Title, new { @class = "col-lg-1 control-label" }) <div class="col-lg-9"> @Html.DisplayFor(model => model.Title, new { @class = "form-control" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.Author, new { @class = "col-lg-1 control-label" }) <div class="col-lg-9"> @Html.DisplayFor(model => model.Author, new { @class = "form-control" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.ISBN, new { @class = "col-lg-1 control-label" }) <div class="col-lg-9"> @Html.DisplayFor(model => model.ISBN, new { @class = "form-control" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.Published, new { @class = "col-lg-1 control-label" }) <div class="col-lg-9"> @Html.DisplayFor(model => model.Published, new { @class = "form-control" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.AddedDate, new { @class = "col-lg-1 control-label" }) <div class="col-lg-9"> @Html.DisplayFor(model => model.AddedDate, new { @class = "form-control" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.ModifiedDate, new { @class = "col-lg-1 control-label" }) <div class="col-lg-9"> @Html.DisplayFor(model => model.ModifiedDate, new { @class = "form-control" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.IP, new { @class = "col-lg-1 control-label" }) <div class="col-lg-9"> @Html.DisplayFor(model => model.IP, new { @class = "form-control" }) </div> </div> @using (Html.BeginForm()) { <div class="form-group"> <div class="col-lg-1"></div> <div class="col-lg-9"> <input type="submit" value="Delete" class="btn btn-danger" /> @Html.ActionLink("Back to List", "Index", null, new { @class = "btn btn-success" }) </div> </div> } </div> </div> </div>
Source: https://habr.com/ru/post/238737/
All Articles