I've got an layered design in my webapplication with an generic service and repository construction. I want to use code first so I can code my entities and then create/update my database. However I can't seem to get it working. I'm new to the code first concept with generating the database and seeding it, so it could very well be something obvious;-)
My application design is as following.
- Website
- Website.DAL
- Website.TESTS (not used yet)
The website.DAL project contains my generic service and repository, as well as DataContext and my entities. The idea is that I can instantiate an generics ervice inside my controller of an certain entity. The service can contain more functions to do calculations etc.. and the repository is only intended to handle the CRUD-actions. The website project ofcourse has an reference to the Website.DAL project and also EF5 is installed in both project through NuGet.
The DataContext looks like this:
using System.Data.Entity;
using System.Web;
using Website.DAL.Entities;
namespace Website.DAL.Model
{
public class MyContext : DbContext
{
public IDbSet<Project> Projects { get; set; }
public IDbSet<Portfolio> Portfolios { get; set; }
/// <summary>
/// The constructor, we provide the connectionstring to be used to it's base class.
/// </summary>
public MyContext()
: base("MyConnectionstringName")
{
//MyContext.Database.Initialize(true);
//if (HttpContext.Current.IsDebuggingEnabled)
//{
// //Database.SetInitializer<MyContext>(new DatabaseInitializer());
// Database.SetInitializer<MyContext>(null);
//}
//else
//{
// //Database.SetInitializer<MyContext>(new CreateInitializer());
//}
}
static MyContext()
{
Database.SetInitializer<MyContext>(null);
}
/// <summary>
/// This method prevents the plurarization of table names
/// </summary>
/// <param name="modelBuilder"></param>
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<System.Data.Entity.ModelConfiguration.Conventions.PluralizingTableNameConvention>();
}
//public void Seed(MyContextContext)
//{
// // Normal seeding goes here
// Context.SaveChanges();
//}
}
}
I've also created an DatabaseInitialiser class which is currently empty, but the idea ofcourse is to make it seed my database when it's created or updated.
The DatabaseInitialiser class looks like this:
using System.Data.Entity;
using Website.DAL.Model;
namespace Website.DAL
{
public class DatabaseInitializer : DropCreateDatabaseIfModelChanges<MyContext>
{
public DatabaseInitializer()
{
}
protected override void Seed(MyContextcontext)
{
//TODO: Implement code to seed database
//Save all changes
context.SaveChanges();
}
}
}
Since the GenericService isn't relevant to the question i'll leave it out since it's currenlty only making direct calls to the repository without any specific business intelligence.
The generic repository used looks like this. Things still need to be improved here, but it works for now.
GenericRepository
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Website.DAL.Model;
using Website.DAL.RepositoryInterfaces;
namespace Website.DAL.Repositories
{
public class GenericRepository<TEntity> : IGenericRepository<TEntity> where TEntity : class
{
#region Implementation of IRepository<TEntity>
//protected SceObjectContext DataContext;
//protected ObjectContext DataContext;
private MyContext _context;
//private IObjectSet<T> ObjectSet;
private DbSet<TEntity> _dbSet;
public GenericRepository()
{
//DataContext = SceObjectContext.Current;
//DataContext = new ObjectContext("dbConnection");
_context = new MyContext();
//ObjectSet = DataContext.CreateObjectSet<T>();
_dbSet = _context.Set<TEntity>();
}
/// <summary>
/// Inserts a new object into the database
/// </summary>
/// <param name="entity">The entity to insert</param>
public void Insert(TEntity entity)
{
//var entitySetName = GetEntitySetName(typeof(T));
//DataContext.AddObject(entitySetName, entity);
_dbSet.Add(entity);
}
/// <summary>
/// Deletes the specified entity from the database
/// </summary>
/// <param name="entity">The object to delete</param>
public void Delete(TEntity entity)
{
//DataContext.DeleteObject(entity);
if (_context.Entry(entity).State == System.Data.EntityState.Detached)
{
_dbSet.Attach(entity);
}
_dbSet.Remove(entity);
}
/// <summary>
/// Saves all pending chances to the database
/// </summary>
public void Save()
{
_context.SaveChanges();
}
/// <summary>
/// Retrieves the first object matching the specified query.
/// </summary>
/// <param name="where">The where condition to use</param>
/// <returns>The first matching object, null of none found</returns>
public TEntity First(Expression<Func<TEntity, bool>> @where)
{
return _dbSet.FirstOrDefault(where);
}
/// <summary>
/// Gets a list of all objects
/// </summary>
/// <returns>An strong typed list of objects</returns>
public IEnumerable<TEntity> GetAll()
{
return _dbSet.AsEnumerable<TEntity>();
}
/// <summary>
/// Returns ans iQueryable of the matching type
/// </summary>
/// <returns>iQueryable</returns>
public IQueryable<TEntity> AsQueryable()
{
return _dbSet.AsQueryable();
}
#endregion
}
}
I've got two entities which i've created. Portfolio is one of them which is displayed belowd. Project is the second one which just is an simple POCO class with an Id and a few properties.
Portfolio.cs
public class Portfolio
{
[Key]
public Guid Id { get; set; }
public String Name { get; set; }
public DateTime StartDate { get; set; }
public DateTime? EndDate { get; set; }
public bool IsPublished { get; set; }
public virtual ICollection<Project> Projects { get; set; }
}
All the classes above are maintained in my Website.DAL project. The Global.asax in my Website project contains some code calling the initialiser which, as far as I know, should make sure the seeding can be done in the near future and maintain the database table.
Global.asax
try
{
//Regenerate database if needed.
//Database.SetInitializer<MyContext>(new DropCreateDatabaseIfModelChanges<MyContext>());
//Database.SetInitializer(new DatabaseInitializer());
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<BorloContext>());
//Database.SetInitializer<MyContext>(new MigrateDatabaseToLatestVersion<MyContext>());
}
catch (Exception)
{
throw;
}
Just for the sake of it i've got a piece of code in my HomeController which should get an id of all portfolio items.
var list = _portfolioService.GetAll();
The following things are happening when debugging through the code;
- Initialiser code in Global.asax passes.
- Constructor for databaseinitialiser is called
- Code in homecontroller doesn't throw an exception. But when adding an watch to the call to '_portfolioService.GetAll();' i'm getting the following exception;
I can't figure out what is going wrong here. Ofcourse the exception isn't good but I can't view the inner exception since it isn't giving me one. What could I possibly do to get this working? Or isn't the thing I want to achieve not possible and should the DAL-layer be merged into the website to get the code generation working?
UPDATE 1:
Okay, i've changed the following line in my context
Database.SetInitializer<MyContext>(null);
To
Database.SetInitializer<MyContext>(new DatabaseInitializer());
Now i'm getting this error and stacktrace when debugging the '_portfolioService.GetAll();' call in the homecontroller
Error:
Model compatibility cannot be checked because the database does not contain model metadata. Model compatibility can only be checked for databases created using Code First or Code First Migrations.
bij System.Data.Entity.Internal.ModelCompatibilityChecker.CompatibleWithModel(InternalContext internalContext, ModelHashCalculator modelHashCalculator, Boolean throwIfNoMetadata)
bij System.Data.Entity.Internal.InternalContext.CompatibleWithModel(Boolean throwIfNoMetadata)
bij System.Data.Entity.Database.CompatibleWithModel(Boolean throwIfNoMetadata)
bij System.Data.Entity.DropCreateDatabaseIfModelChanges`1.InitializeDatabase(TContext context)
bij System.Data.Entity.Database.<>c__DisplayClass2`1.<SetInitializerInternal>b__0(DbContext c)
bij System.Data.Entity.Internal.InternalContext.<>c__DisplayClass8.<PerformDatabaseInitialization>b__6()
bij System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
bij System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
bij System.Data.Entity.Internal.LazyInternalContext.<InitializeDatabase>b__4(InternalContext c)
bij System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input)
bij System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action)
bij System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase()
bij System.Data.Entity.Internal.InternalContext.Initialize()
bij System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
bij System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
bij System.Data.Entity.Internal.Linq.InternalSet`1.GetEnumerator()
bij System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator()
bij System.Linq.SystemCore_EnumerableDebugView`1.get_Items()