简体   繁体   中英

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.

I have a class library project titled "Dashboard.Data", where I generated a code-first to existing database. 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:

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.

My 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. 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). 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?

EDIT 1

I've noticed that the MVC project creates a new and empty .mdf file in the App_Data folder. I have this connection string in both my MVC's web.config as well as the app.config in my DAL

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|?

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.

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. 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

SQL Express Connection string - Relative to application location

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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