简体   繁体   English

使用实体框架和存储库正确实施DAL

[英]Correct implementation of DAL with Entity Framework & Repository

I'm having some difficulty and confusion setting up my MVC/WebAPI project with a separate DAL project. 我在使用单独的DAL项目设置MVC / WebAPI项目时遇到了一些困难和困惑。

I have a class library project titled "Dashboard.Data", where I generated a code-first to existing database. 我有一个名为“ Dashboard.Data”的类库项目,在该项目中,我对现有数据库生成了代码优先的代码。 This class library now contains all my model classes as well as my Repository. 现在,该类库包含我的所有模型类以及我的存储库。 I've yet to implement a generic repository but what I have so far should still work. 我尚未实现通用存储库,但到目前为止我仍然可以使用。

Repository: 库:

namespace Dashboard.Data.Repository
{
    public class ProductRepository : IProductRepository, IDisposable
    {
        private DatabaseContext _context;
        public ProductRepository()
        {
            _context = new DatabaseContext();
        }
        public ProductRepository(DatabaseContext context)
        {
            this._context = context;
        }

        public async Task<IEnumerable<Department>> GetDepartmentList()
        {
            return await _context.Departments.ToListAsync();
        }
        protected void Dispose(bool disposing)
        {
            if (disposing)
                if (_context != null)
                {
                    _context.Dispose();
                    _context = null;
                }
        }
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
}

IRepository: IRepository:

namespace Dashboard.Data.Repository
{
    public interface IProductRepository: IDisposable
    {
        Task<IEnumerable<Department>> GetDepartmentList();
    }
}

Now i have a separate MVC/WebAPI project, where I try to use the repository. 现在,我有一个单独的MVC / WebAPI项目,在这里尝试使用存储库。

My APIController: 我的APIController:

namespace Dashboard.Controllers
{
    public class ProductsAPIController : ApiController
    {
        protected IProductRepository repository { get; set; }
        public ProductsAPIController()
        {
            this.repository = new ProductRepository();
        }

        [Route("api/Departments")]
        public async Task<IHttpActionResult> GetDepartmentList()
        {
            var departments = await repository.GetDepartmentList();
            return Ok(departments);
        }       
    }
}

However, when I call the GetDepartmentList() in the api, i notice that my repository's context contains no data. 但是,当我在api中调用GetDepartmentList()时,我注意到我的存储库上下文不包含任何数据。 It shows a "Enumeration yielded no results" message. 它显示“枚举未产生结果”消息。

I'm worried that i've just confused myself when setting up my solution. 我担心设置解决方案时会感到困惑。

Could it be an incorrect connection string? 可能是错误的连接字符串吗? Though it does look like it's able to see the database. 虽然看起来确实可以查看数据库。 I feel like I just have improper injection of the context, but not sure where or how to fix this issue. 我觉得我只是注入了不正确的上下文,但不确定在哪里或如何解决此问题。

Also, I am running off a local database file (.mdf). 另外,我正在运行本地数据库文件(.mdf)。 Where should this file be located? 该文件应位于何处? I currently have it in the Dashboard.Data folder...should it be in the App_Data folder of the main project? 我目前在Dashboard.Data文件夹中有它...应该在主项目的App_Data文件夹中吗?

EDIT 1 编辑1

I've noticed that the MVC project creates a new and empty .mdf file in the App_Data folder. 我注意到MVC项目在App_Data文件夹中创建了一个新的空.mdf文件。 I have this connection string in both my MVC's web.config as well as the app.config in my DAL 我的MVC的web.config和DAL中的app.config都有此连接字符串

My connection string: 我的连接字符串:

 <connectionStrings>
        <add name="NriDatabaseContext" connectionString="data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\NRI_Database.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
      </connectionStrings>

is it because of |DataDirectory|? 是因为| DataDirectory |吗?

Not sure if this is the correct way to implement, but I went ahead and moved the .mdf to App_Data in my MVC project, and re-created the connection strings to point to that file. 不知道这是否是正确的实现方式,但是我继续将Mmd项目中的.mdf移至App_Data,然后重新创建了指向该文件的连接字符串。

Migrations seem to work now, as well as data access. 迁移和数据访问现在似乎都可以进行。 Hopefully this is the correct solution. 希望这是正确的解决方案。

The DataDirectory part of the connection string will automatically be substituted for the App_Data directory within your web application. 连接字符串的DataDirectory部分将自动替换Web应用程序中的App_Data目录。 It is possible to use a different location for your database file by using a relative path or changing the location within code. 通过使用相对路径或更改代码中的位置,可以为数据库文件使用其他位置。

The following links should provide more detailed information: 以下链接应提供更多详细信息:

MSDN MSDN

SQL Express Connection string - Relative to application location SQL Express连接字符串-相对于应用程序位置

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

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