Marcin Marcin - 3 months ago 9
ASP.NET (C#) Question

EF exception when trying to seed database

I followed this tutorial to create my own application: http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application

When I start to debug and try to open tab of Players list, its equivalent to Student tab in these tutorial, I got following exception:


Exception Details: Object of type 'AzsPkInz.DAL.AZSContext' cannot be converted to type 'System.Data.Entity.IDatabaseInitializer`1[AzsPkInz.DAL.AZSContext]'.

Source Error:


  1. Line 19: public ActionResult Index()

  2. Line 20: {

  3. Line 21: return View(db.Players.ToList());

  4. Line 22: }




This is
AZSContext
source:

public class AZSContext : DbContext
{
public AZSContext() : base("AZSContext")
{
}

public DbSet<Player> Players { get; set; }
public DbSet<Training> Trainings { get; set; }
public DbSet<Enrollment> Enrollments { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}


And this is a
Player
model:

public class Player
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime BirthDate { get; set; }
public DateTime JoinDate { get; set; }

public virtual ICollection<Enrollment> Enrollemnts { get; set; }
}


Any idea's what I have done wrong?

Answer

Make sure that in your web config the databaseInitializer element points to a IDatabaseInitializer (such as SchoolInitializer) not a AZSContext.

<contexts>
  <context 
      type="ContosoUniversity.DAL.SchoolContext, ContosoUniversity">
    <databaseInitializer type="ContosoUniversity.DAL.SchoolInitializer, ContosoUniversity" />
  </context>
</contexts>