Asp.net mvc MVC应用中数据库的UnitOfWork模式存储库

Asp.net mvc MVC应用中数据库的UnitOfWork模式存储库,asp.net-mvc,design-patterns,unit-of-work,Asp.net Mvc,Design Patterns,Unit Of Work,今天,我想为数据库连接实现存储库模式+工作单元模式。我下面的代码正确吗??因为这是我的第一个数据库连接工作实现单元 第一个存储库: public class NotesRepository : INotesRepository { private DatabaseContext context; public NotesRepository(DatabaseContext context) { this.context = context; }

今天,我想为数据库连接实现存储库模式+工作单元模式。我下面的代码正确吗??因为这是我的第一个数据库连接工作实现单元

第一个存储库:

public class NotesRepository : INotesRepository
{
    private DatabaseContext context;

    public NotesRepository(DatabaseContext context)
    {
        this.context = context;
    }

    public IQueryable<Notes> GetAllNotes()
    {
        return (from x in context.Notes
                select x);
    }
}
public class CommentsRepository : ICommentsRepository
{
    private DatabaseContext context;

    public CommentsRepository(DatabaseContext context)
    {
        this.context = context;
    }

    public IQueryable<Comments> GetAllComments()
    {
        return (from x in context.Comments
                select x);
    }
}
和控制器,我可以在其中使用多个存储库和单个数据库连接:

public class UnitOfWork
{
    private DatabaseContext context = new DatabaseContext();
    private INotesRepository notesRepository;
    private ICommentsRepository commentsRepository;

    public INotesRepository NotesRepository
    {
        get
        {
            if (this.notesRepository == null)
            {
                this.notesRepository = new NotesRepository(context);
            }
            return notesRepository;
        }
    }

    public ICommentsRepository CommentsRepository
    {
        get
        {
            if (this.commentsRepository == null)
            {
                this.commentsRepository = new CommentsRepository(context);
            }
            return commentsRepository;
        }
    }
}
public class HomeController : Controller
    {
        private UnitOfWork unitOfWork = new UnitOfWork();        

        public ViewResult Index()
        {
            var a = unitOfWork.NotesRepository.GetAllNotes();
            var b = unitOfWork.CommentsRepository.GetAllComments();

            return View();
        }
    }

您的实现非常正确:)

但我建议您使用IUnitOfWork接口并在构造函数中传递DatabaseContext实例。

另一件事是在UnitOfWork中使用SaveChanges方法将数据提交到数据库。