如何在ASP.NET MVC中使用通用存储库创建体系结构 [英] How to create architecture with generic repository in ASP.NET MVC

查看:73
本文介绍了如何在ASP.NET MVC中使用通用存储库创建体系结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Asp.net中的Generic存储库创建架构mvc 





我拥有什么试过:



想为我的MVC项目创建通用存储库

解决方案

如果你想要创建代码第一种方法然后按照下面的代码创建通用存储库模式



 [表(类别)] 
public class Category
{
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity),Key()]
public int Id {get;组; }

[必需]
公共字符串名称{get;组; }

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

[表(BlogPosts)]
公共类BlogPost
{
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity),Key()]
public int Id {get;组; }
public string Title {get;组; }
public string Content {get;组; }
public DateTime PublishDate {get;组; }

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

公共虚拟类别类别{get;组; }
}





公共密封类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;组; }
public DbSet< Category>类别{get;组; }
public DbSet< StudentModel>学生模特{get;组; }
}





您需要为UnitOfWork和Repository创建接口,如下所示

{
IRepository< T>存储库< T>()其中T:class;
void SaveChanges();
void BeginTransaction();
void RollBackTransaction();
void CommitTransaction();
}

公共接口IRepository< T>
{
IEnumerable< T> GetAll(Func< T,bool> predicate = null);
T Get(Func< T,bool>谓词);
void Add(T entity);
void Attach(T entity);
void删除(T实体);
}





你需要实现这两个界面



公共类UnitOfWork:IUnitOfWork 
{
private readonly BlogContext entities = null;

private DbContextTransaction ObjectSetTransaction {get;组; }

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

//私人词典<类型,对象> repositories = new Dictionary< Type,object>();

// [依赖]
public IRepository< T>存储库< T>()其中T:class
{
返回新的存储库< T>(实体);
//返回新的存储库< T>(entities.Set< T>());

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

// IRepository< T> repository = new Repositories< T>(实体);
//rereories.Add(typeof(T),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 dispos = 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);
}
}



公共类存储库< T> :IRepository< T>其中T:class
{
// private readonly BlogContext entities = null;
private readonly IDbSet< T> objectSet = null;

公共存储库(BlogContext实体)
{
//this.entities = entities;
this.objectSet = entities.Set< T>();
}

公共存储库(IDbSet< T> objectSet)
{
this.objectSet = objectSet;
}

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

返回objectSet.AsEnumerable();
}

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

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

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

public void删除(T实体)
{
objectSet.Remove(entity);
}
}





现在,您可以使用创建对象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 =Ahmedab​​ad,PublishDate = DateTime.UtcNow,Title =City});
unitOfWork.SaveChanges();

unitOfWork.CommitTransaction();
}
catch
{
unitOfWork.RollBackTransaction();
}
返回RedirectToAction(List,Home);
}

return View(model);
}


How to create architecture with Generic repository in Asp.net mvc



What I have tried:

Wanted to created generic repository for my MVC project

解决方案

If you want to create code first approach then follow below code to create generic repository pattern

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


这篇关于如何在ASP.NET MVC中使用通用存储库创建体系结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆