I have created an application that uses multiple Visual Studio Projects for the layers of an ASP.NET MVC application. I have got a Data Access Layer, Business Logic Laye and Presentation Layer.
The solution Looks like this:
I am using a Repository that look like this:
public class RepositoryDal: IRepositoryDal
{
private readonly DatabaseContext context;
public RepositoryDal()
{
context = new DatabaseContext();
}
public T Add<T>(T entity) where T : Entity
{
return context.Set<T>().Add(entity);
}
public void Delete<T>(T entity) where T : Entity
{
context.Set<T>().Remove(entity);
}
public IQueryable<T> GetAll<T>() where T : Entity
{
return context.Set<T>();
}
public T GetById<T>(int id) where T : Entity
{
return context.Set<T>().FirstOrDefault(x => x.Id == id);
}
public bool HasChanges()
{
return context.ChangeTracker.HasChanges();
}
public void Save()
{
context.SaveChanges();
}
}
I am calling the methods of this repository from my Business logic layer:
public class BookBll: IBookBll
{
private readonly IRepositoryDal _repositoryDal;
public BookBll()
{
_repositoryDal = new RepositoryDal();
}
public Book AddBook(Book book)
{
book = _repositoryDal.Add(book);
_repositoryDal.Save();
return book;
}
...
}
This works. But if I do something like this it will not work correctly:
public class ShelfBll: IShelfBll
{
private readonly IRepositoryDal _repositoryDal;
public ShelfBll()
{
_repositoryDal = new RepositoryDal();
}
public Shelf AddShelf(Shelf shelf)
{
shelf = _repositoryDal.Add(shelf);
_repositoryDal.Save();
return shelf;
}
...
}
The problem is that I connect the book to a shelf and the shelf is retrieved via another Business logic layer class. By doing this I am loosing the Entity Framework context. What happens is that the application will not connect to the shelf, but it will create a new shelf. That means after this I will have two shelves with the same name.
How can I solve this problem?
