Click here to Skip to main content
15,029,837 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
How to create generic repository pattern in asp.net mvc

What I have tried:

I am trying to create repository patterns but not able to create
Posted
Updated 30-Jul-17 21:03pm
Comments
K I R T I 1-Aug-17 1:12am
   
namespace WebApplication1.Controllers
{
public class VideoController : Controller
{
// GET: Video
public ActionResult Index()
{
VideoContext entity = new VideoContext();
var data = entity.Videos.ToList();
return View(data);
}

// GET: Video/Create
public ActionResult Create()
{
return View();
}

// POST: Video/Create
[HttpPost]
public ActionResult Create(VideoViewModel model)
{
try
{
if (ModelState.IsValid)
{
var uploadFilesDir = Server.MapPath("~/Video");
var fileSavePath = Path.Combine(uploadFilesDir, model.file.FileName);

int length = model.file.ContentLength;
byte[] video = new byte[length];

model.file.InputStream.Read(video, 0, length);
model.file.SaveAs(fileSavePath);

Video.DataModel.Video obj = new Video.DataModel.Video();
obj.VideoName = model.VideoName;
obj.VideoPath = model.file.FileName;
obj.Image = video;

VideoContext entity = new VideoContext();
entity.Videos.Add(obj);
entity.SaveChanges();

return RedirectToAction("Index");
}

return View();
}
catch (Exception ex)
{
return View();
}
}

[HttpGet]
public ActionResult PlayVideo(int VideoId)
{
VideoContext entity = new VideoContext();
var data = entity.Videos.Where(x => x.VideoId.Equals(VideoId)).FirstOrDefault();
var base64 = Convert.ToBase64String(data.Image);
var imgSrc = String.Format("data:video/mp4;base64,{0}", base64);

data.VideoPath = imgSrc;

return PartialView(data);
}

public ActionResult CreateNew()
{
return View();
}
}
}

If you want to create code first approach then follow below code to create generic repository pattern
 
<pre>[Table("Categories")]
    public class Category
    {
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity), Key()]
        public int Id { get; set; }

        [Required]
        public string Name { get; set; }

        public virtual ICollection<BlogPost> BlogPosts { get; set; }
    }

[Table("BlogPosts")]
    public class BlogPost
    {
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity), Key()]
        public int Id { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }
        public DateTime PublishDate { get; set; }

        [ForeignKey("Category")]
        public int CategoryId { get; set; }

        public virtual Category Category { get; set; }
    }


public sealed class BlogContext : DbContext
    {
        static BlogContext()
        {
            Database.SetInitializer<BlogContext>(null);
        }

        public BlogContext()
            : base("name=TABFusionRMSContext")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        }

        public DbSet<BlogPost> BlogPosts { get; set; }
        public DbSet<Category> Categories { get; set; }
        public DbSet<StudentModel> StudentModels { get; set; }
    }


You need to create Interface for UnitOfWork And Repository like below

public interface IUnitOfWork : IDisposable
  {
      IRepository<T> Repository<T>() where T : class;
      void SaveChanges();
      void BeginTransaction();
      void RollBackTransaction();
      void CommitTransaction();
  }

  public interface IRepository<T>
  {
      IEnumerable<T> GetAll(Func<T, bool> predicate = null);
      T Get(Func<T, bool> predicate);
      void Add(T entity);
      void Attach(T entity);
      void Delete(T entity);
  }


You need to implement this two interface

public class UnitOfWork : IUnitOfWork
    {
        private readonly BlogContext entities = null;

        private DbContextTransaction ObjectSetTransaction { get; set; }

        public UnitOfWork()
        {
            entities = new BlogContext();
        }

        //private Dictionary<Type, object> repositories = new Dictionary<Type, object>();

        //[Dependency]
        public IRepository<T> Repository<T>() where T : class
        {
            return new Repositories<T>(entities);
            //return new Repositories<T>(entities.Set<T>());

            //if (repositories.Keys.Contains(typeof(T)) == true)
            //{
            //    return (IRepository<T>)repositories[typeof(T)];
            //}

            //IRepository<T> repository = new Repositories<T>(entities);
            //repositories.Add(typeof(T), repository);
            //return repository;
        }

        public void SaveChanges()
        {
            entities.SaveChanges();
        }

        public void BeginTransaction()
        {
            ObjectSetTransaction = entities.Database.BeginTransaction();
        }

        public void RollBackTransaction()
        {
            ObjectSetTransaction.Rollback();
            ObjectSetTransaction.Dispose();

        }
        public void CommitTransaction()
        {
            ObjectSetTransaction.Commit();
            ObjectSetTransaction.Dispose();
        }

        private bool disposed = false;

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    entities.Dispose();
                }
            }

            this.disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }



 public class Repositories<T> : IRepository<T> where T : class
    {
        //private readonly BlogContext entities = null;
        private readonly IDbSet<T> objectSet = null;

        public Repositories(BlogContext entities)
        {
            //this.entities = entities;
            this.objectSet = entities.Set<T>();
        }

        public Repositories(IDbSet<T> objectSet)
        {
            this.objectSet = objectSet;
        }

        public IEnumerable<T> GetAll(Func<T, bool> predicate = null)
        {
            if (predicate != null)
            {
                return objectSet.Where(predicate);
            }

            return objectSet.AsEnumerable();
        }

        public T Get(Func<T, bool> predicate)
        {
            return objectSet.FirstOrDefault(predicate);
        }

        public void Add(T entity)
        {
            objectSet.Add(entity);
        }

        public void Attach(T entity)
        {
            objectSet.Attach(entity);
        }

        public void Delete(T entity)
        {
            objectSet.Remove(entity);
        }
    }


Now you can use this classes in your controller using creating object unitofwork

  [HttpPost]
        public ActionResult Create(Category model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    UnitOfWork unitOfWork = New UnitOfWork();

                    unitOfWork.BeginTransaction();

                    unitOfWork.Repository<Category>().Add(model);
                    unitOfWork.SaveChanges();

                    unitOfWork.Repository<BlogPost>().Add(new BlogPost { CategoryId = model.Id, Content = "Ahmedabad", PublishDate = DateTime.UtcNow, Title = "City" });
                    unitOfWork.SaveChanges();

                    unitOfWork.CommitTransaction();
                }
                catch
                {
                    unitOfWork.RollBackTransaction();
                }
                return RedirectToAction("List", "Home");
            }

            return View(model);
        }


        [Required]
        public HttpPostedFileBase file { get; set; }

<div class="modal-dialog">
    <!-- Modal content-->
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">&times;</button>
            <h4 class="modal-title">@Model.VideoName</h4>
        </div>
        <div class="modal-body">
            <video width="100%" controls autoplay="autoplay">
                @*<source id="video" src='@Url.Content("~/Video/" + Model.VideoPath)' type="video/mp4">*@
                <source id="video" src="@Model.VideoPath" >
                @*<source id="video" src="@Url.Action("GetVideo", "Video", new { VideoId = Model.VideoId } )">*@
            </video>
        </div>
    </div>
</div>

<div id="myModal" class="modal fade" role="dialog">

var uploadFilesDir = Server.MapPath("~/Video");
                    var fileSavePath = Path.Combine(uploadFilesDir, model.file.FileName);

                    int length = model.file.ContentLength;
                    byte[] video = new byte[length];

                    model.file.InputStream.Read(video, 0, length);
                    model.file.SaveAs(fileSavePath);

                    Video.DataModel.Video obj = new Video.DataModel.Video();
                    obj.VideoName = model.VideoName;
                    obj.VideoPath = model.file.FileName;
                    obj.Image = video;

                    VideoContext entity = new VideoContext();
                    entity.Videos.Add(obj);
                    entity.SaveChanges();

 function PlayVideo(VideoId) {
        $.ajax({
            url: '/Video/PlayVideo',
            datatype: "html",
            type: "Get",
            data: { 'VideoId': VideoId },
            contenttype: 'application/json; charset=utf-8',
            success: function (data) {
                $("#myModal").html(data);
                $("#myModal").modal("show");
            },
            error: function (xhr) {
                alert('error');
            }
        });
    }

<pre>  <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="1073741824" />
      </requestFiltering>
    </security>

<httpRuntime maxRequestLength="1048576" executionTimeout="3600" targetFramework="4.5" />
   
v4
Hedre is a great article to start with: Generic Repository Pattern in ASP.NET MVC[^]
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900