对于asp.net的MVC好存储库模式 [英] Good repository pattern for asp.net mvc

查看:115
本文介绍了对于asp.net的MVC好存储库模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经实现了我的asp.net MVC Web应用程序的存储库模式...但我想知道这是一个很好的资源库的模式或仍可我改善它更多...

I have implemented a repository pattern in my asp.net mvc web application... But i want to know is this a good repository pattern or still can i improve it more...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using TaxiMVC.BusinessObjects;

namespace TaxiMVC.Models
{
    public class ClientRepository
    {
        private TaxiDataContext taxidb = new TaxiDataContext();
        Client cli = new Client();

        //Get all Clients
        public IQueryable<ClientBO> FindAllClients(int userId)
        {
            var client = from c in taxidb.Clients
                         where c.CreatedBy == userId && c.IsDeleted == 0 
                         select new ClientBO()
                         {
                             ClientId = c.ClientId,
                             ClientName= c.ClientName,
                             ClientMobNo= Convert.ToString(c.ClientMobNo),
                             ClientAddress= c.ClientAddress
                         };
            return client;
        }

        //Get Client By Id
        public ClientBO FindClientById(int userId,int clientId)
        {
            return (from c in taxidb.Clients
                    where c.CreatedBy == userId && c.ClientId == clientId && c.IsDeleted == 0
                         select new ClientBO()
                         {
                             ClientId = c.ClientId,
                             ClientName= c.ClientName,
                             ClientMobNo= Convert.ToString(c.ClientMobNo),
                             ClientAddress= c.ClientAddress
                         }).FirstOrDefault();
        }

        //Insert a new client
        public bool ClientInsert(ClientBO clientBO)
        {
            cli.ClientName = clientBO.ClientName;
            cli.ClientMobNo = Convert.ToInt64(clientBO.ClientMobNo);
            cli.ClientAddress = clientBO.ClientAddress;
            cli.CreatedDate = clientBO.CreatedDate;
            cli.IsDeleted = clientBO.IsDeleted;
            cli.CreatedBy = clientBO.CreatedBy;

            if (!taxidb.Clients.Where(c => c.ClientMobNo == cli.ClientMobNo).Any())
            {
                taxidb.Clients.InsertOnSubmit(cli);
                taxidb.SubmitChanges();
                return true;
            }
            else
                return false;
        }

      //Client Update
        public ClientBO updateClient(ClientBO clientBO)
        {
            var table = taxidb.GetTable<Client>();
            var cli = table.SingleOrDefault(c => c.ClientId == clientBO.ClientId && c.CreatedBy==clientBO.CreatedBy);
            cli.ClientName = clientBO.ClientName;
            cli.ClientMobNo = Convert.ToInt64(clientBO.ClientMobNo);
            cli.ClientAddress = clientBO.ClientAddress;
            taxidb.SubmitChanges();
            return clientBO;
        }

        //Delete Clients
        public bool deleteClients(string Ids, int userId)
        {
            var idsToDelete = Ids.Split(',').Select(c => Convert.ToInt32(c));
            var clientsToDelete = taxidb.Clients.Where(c => idsToDelete.Contains(c.ClientId));
            foreach (var client in clientsToDelete)
            {
                client.IsDeleted = Convert.ToByte(1); 
            }
            taxidb.SubmitChanges();
            return true;
        }
     }
}

和我ClientBo.cs,

and my ClientBo.cs,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace TaxiMVC.BusinessObjects
{
    public class ClientBO
    {
        public int ClientId { get; set; }
        public string ClientName { get; set; }
        public string ClientMobNo { get; set; }
        public string ClientAddress { get; set; }
        public DateTime CreatedDate { get; set; }
        public byte IsDeleted { get; set; }
        public int CreatedBy { get; set; }
    }
}

我没有在这里实现一个IRepository ...我应该已经实现,或应我的仓库仍然可以改善......任何建议....

I Didn't implement an IRepository here... Should i ve to implement it or should my repository can still be improved... Any suggestion....

推荐答案

嗯,肯定是有几件事情,我会做些什么来改善这一点。

Hmm, there is definitely a couple of things that I would do to improve this.

第一:我要定义你的版本库实现一个接口。这可以让你在依赖更大的控制权,而当与反转控制/依赖注入(IOC / DI)框架的结合,这是巨大的改善。 IOC / DI框架包括StructureMap或NInjet。有斯科特Hanselman的一读,这是一个pretty COM prehensive列表。

First: I would define an interface for your Repository to implement. This allows you greater control over dependencies, and when coupled with a Inversion Of Control/Dependency Injection (IOC/DI) framework, this is hugely improved. IOC/DI frameworks include StructureMap or NInjet. Have a read of this from Scott Hanselman, it's a pretty comprehensive list.

您的界面可能是这样的:

Your interface may look like:

public interface IClientRepository
{
    IQueryable<ClientBO> FindAllClients(int userId);
    ClientBO FindClientById(int userId, int clientId);
    ClientInsert(ClientBO clientBO);
    ClientBO updateClient(ClientBO clientBO);
    bool deleteClients(string Ids, int userId);
}

二:不要做你的业务对象( ClientBO )以持久化对象(客户端你的仓库内)的转换。这意味着,如果你对BO的任何变化,那么你就需要去通过并改变你的整个资料库。

Second: don't do your Business Object (ClientBO) to persistent object (Client) conversion inside of your repository. This means that if you make any changes to your BO, then you'll need to go through and change your entire repository.

我注意到你有很多左右分配code,如的。

I notice you have a lot of left-right assignment code, eg.

cli.ClientName = clientBO.ClientName;

我会认真调查使用 AutoMapper 的。它使这个猴code的轻松了许多地狱。

I would seriously investigate the use of AutoMapper. It makes this "monkey code" a hell of a lot easier.

编辑:<一href=\"http://www.bengtbe.com/blog/post/2009/04/14/Using-AutoMapper-to-map-view-models-in-ASPNET-MVC.aspx\">Here是介绍如何使用AutoMapper删除左右分配code博客文章。

第三:您的命名结构更是遍布店。我们有: FindAllClients() ClientInsert() updateClient()都在一个班。命名非常非常差。为了您的资料库,尝试在什么将在DB一侧发生的方法建模。尝试添加插入删除的FindAll GETALL 查找 GETALL 的SaveChanges ,方法名。

Third: Your naming structure is all over the shop. We have: FindAllClients(), ClientInsert(), updateClient() all in the one class. Very very poor naming. For your repository, try to model your methods on what will be happening on the DB side. Try Add or Insert, Delete, FindAll or GetAll, Find or GetAll, SaveChanges, method names.

不要追加/ prePEND类型的方法名,你是在 ClientRepository ,它意味着你将添加或获取<的。

Don't append/prepend the type to the method name, as your are in the ClientRepository, it's implied that you'll be adding or getting Client's.

第四:您的混合您的LINQ的语法。在一些地方,您使用声明查询语法等场所的使用方法的语法。挑选1到处使用它。

Fourth: Your mixing your LINQ syntax. In some places your using the declarative query syntax and other places your using the method syntax. Pick 1 and use it everywhere.

第五::此行让我担心:

 if (!taxidb.Clients.Where(c => c.ClientMobNo == cli.ClientMobNo).Any())

这看起来很像业务逻辑给我。不是,应该是在库中。要么声明列是 UNIQUE 在DB,或移动逻辑到另一个验证层。

This looks suspiciously like business logic to me. Not something that should be in the repository. Either declare the column to be UNIQUE in the DB, or move that logic into another validation layer.

这些是我跳出了主要的事情。一对夫妇的这些都是个人的preference,但我希望这会有所帮助。

These were the main things that jumped out at me. A couple of these are personal preference, but I hope this helps.

这篇关于对于asp.net的MVC好存储库模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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