简体   繁体   English

LINQ ASP.NET MVC存储库模式的最佳实践是什么

[英]Whats the best practice of linq ASP.NET MVC respository pattern

I'm a junior web developer trying to learn more every day. 我是一名初级的Web开发人员,试图每天学习更多信息。

What it the best practice for you guys to performe MVC repository pattern with Linq? 你们用Linq执行MVC存储库模式的最佳实践是什么?

The one I use: 我用的那个:

Create extra clases with the exact name of my .tt files with CRUD method like getAll(), getOne(), Update(), Delete() filling my own class with the entity framework and returning this, or using the entity framework crude 使用CRUD方法(如getAll(),getOne(),Update(),Delete())用我的.tt文件的确切名称创建额外的分类,将实体框架填充到我自己的类中并返回该类,或使用原始的实体框架

this is an example of what I'm actually doing. 这是我实际上在做的一个例子。

this is my getAll method of my class for example User 这是我类的getAll方法,例如User

public class CEmployee : CResult
{

    public string name{get;set;}
    public string lastname{get;set;}
    public string address{get;set;}

    //Extracode
    public string Fullname // this code is not in the .tt or database
    {
        get
        {
            return name + lastname;
        }
    }

    public <List>CEmployee getAll()
    {
        try
            {
                var result = (from n in db.Employee 
                                select new CEmployee // this is my own class I fill it using the entity
                                {
                                    name = n.name,
                                    lastname = n.lastname,
                                    address = n.address
                                }).ToList();

                                if (result.Count > 0)
                                {
                                    return result;
                                }
                                else
                                {
                                    return new List<CResult>
                                    {
                                        new CResult
                                        {
                                            has_Error = true,
                                            msg_Error = "Element not found!!!!"
                                        }
                                    }
                                }

            }
        catch
            {
                return Exception();
            }


    }
}

that the way I do all thing I return a filled of my type, but on the web I see that people return the entity type normaly, But I do this to manipulate my response, And if I want to return extra information I just have to neste a list for example, whats the best way guys, return mytype or return the entity type ? 这样,我会返回一个填充的类型,但是在网络上,我看到人们通常返回实体类型,但是我这样做是为了操纵我的响应,如果我想返回额外的信息,我只需要例如,嵌套一个列表,伙计们最好的方法是什么,返回mytype或返回实体类型?

PD, I also use this class like my ViewModel.And I do this for all my classes. PD,我也像ViewModel一样使用此类,并且对所有类都这样做。

One of the projects I am currently one uses Dependency Injection to setup the DAL (Data Access Layer.) We also are using an n-Tier approach; 我目前参与的一个项目之一是使用依赖注入来设置DAL(数据访问层)。 this separates the concern of the repository from the Business Logic and Front End. 这将存储库的关注与业务逻辑和前端分开。

So we would start with 4 or so base projects in the application that link to each other. 因此,我们将从应用程序中相互链接的大约4个基础项目开始。 One of that handles the Data Access, this would be your repository; 其中之一处理数据访问,即您的存储库; read up on Ninject for more info on this. 阅读有关Ninject的更多信息。 Our next tier is our Domain which houses the Entities built by the t4 template(.tt files) and also our DTO's (data transfer objects which are flat objects for moving data between layers.) Then we have a service layer, the service layer or business logic layer holds service objects that handle CRUD operations and any data manipulation needed. 我们的下一层是我们的域,其中包含由t4模板(.tt文件)构建的实体,还有我们的DTO(数据传输对象,它们是用于在各层之间移动数据的平面对象)。然后,我们有了服务层,服务层或业务逻辑层包含处理CRUD操作和所需任何数据操作的服务对象。 Lastly we have our front end which is the Model-View-ViewModel layer and handles the controllers and page building. 最后,我们有一个前端,即Model-View-ViewModel层,用于处理控制器和页面构建。

The MVVM calls the services, the service objects call the data access layer and Entity Framework works with Ninject to access the data and its stored in the DTO's as it is moved across layers. MVVM调用服务,服务对象调用数据访问层,而Entity Framework与Ninject一起使用,以访问数据及其在DTO中的移动,并跨层移动。

Now this may seem overly complex depending on the application you are writing, this is built for a highly scalable and expandable web application. 现在,根据您正在编写的应用程序,这似乎过于复杂,它是为高度可扩展和可扩展的Web应用程序而构建的。

I would highly recommend going with a generic repository implementation. 我强烈建议使用通用存储库实现。 The layers between your repository and the controller vary depending on a number of factors (which is kind of a broader/bigger topic) but the generic repository gets you going on a good implementation that is lightweight. 存储库和控制器之间的层取决于许多因素(这是一个更大/更大的主题),但是通用存储库使您可以进行轻量级的良好实现。 Check out this article for a good description of the approach: 查看本文,以获取有关此方法的良好描述:

http://www.asp.net/mvc/tutorials/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application http://www.asp.net/mvc/tutorials/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an- ASP净MVC应用程序

Ideally in a MVC application, you will want to repositories in a different layer like in a separate project, let's call it Data layer. 理想情况下,在MVC应用程序中,您需要将存储库放在不同的层中,例如在单独的项目中,我们将其称为数据层。

You will have an IRepository interface that contain generic method signatures like GetAll, GetById, Create or UpdateById. 您将拥有一个IRepository接口,其中包含通用方法签名,例如GetAll,GetById,Create或UpdateById。 You will also have abstract RepositoryBase class that contain shared implementation such as Add, Update, Delete, GetById, etc. 您还将拥有抽象的RepositoryBase类,该类包含共享的实现,例如Add,Update,Delete,GetById等。

The reason that you use an IRepository Interface is, there are contracts for which your inherited repository class, such as EmployeeRepository in your case, need to provide concrete implementations. 使用IRepository接口的原因是,对于某些合同,您继承的存储库类(例如您的情况下的EmployeeRepository)需要提供具体的实现。 The abstract class serves as a common place for your shared implementation (and override them as you need to). 抽象类是共享实现的常用位置(并根据需要覆盖它们)。

So in your case, what you are doing using LINQ with your DbContext is basically correct, but implementation like your GetAll method should be part of the generic/shared implementation in your abstract class RepositoryBase: 因此,在您的情况下,将LINQ与DbContext一起使用时所做的工作基本上是正确的,但是诸如GetAll方法之类的实现应成为抽象类RepositoryBase中通用/共享实现的一部分:

public abstract class RepositoryBase<T> where T : class
{
    private YourEntities dataContext;
    private readonly IDbSet<T> dbset;

    protected RepositoryBase(IDatabaseFactory databaseFactory)
    {
        DatabaseFactory = databaseFactory;
        dbset = DataContext.Set<T>();
    }

    protected IDatabaseFactory DatabaseFactory
    {
        get;
        private set;
    }

    protected YourEntities DataContext
    {
        get { return dataContext ?? (dataContext = DatabaseFactory.Get()); }
    }
    public virtual T GetById(long id)
    {
        return dbset.Find(id);
    }
    public virtual T GetById(string id)
    {
        return dbset.Find(id);
    }
    public virtual IEnumerable<T> GetAll()
    {
        return dbset.ToList();
    }
}

I would suggest you need to think about whether or not to return an error result object like CResult, and think about if your CEmployee and CResult should exist in this parent-child relationship. 我建议您需要考虑是否返回像CResult这样的错误结果对象,并考虑您的CEmployee和CResult是否应存在于此父子关系中。 Also think about what you want to do with your CResult Class. 还考虑一下您想对CResult类做什么。 It seems to me your CEmployee handles too many tasks in this case. 在我看来,您的CEmployee在这种情况下处理了太多任务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM