我按照本教程创建了自己的应用程序: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

当我开始调试并尝试打开“播放器”列表的选项卡时,其等效于这些教程中的“学生”选项卡,我得到以下异常:


  异常详细信息:无法将类型为“ AzsPkInz.DAL.AZSContext”的对象转换为类型为“ System.Data.Entity.IDatabaseInitializer`1 [AzsPkInz.DAL.AZSContext]”。
  
  源错误:
  
  
  第19行:public ActionResult Index()
  第20行:{
  第21行:return View(db.Players.ToList());
  第22行:}
  


这是AZSContext来源:

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>();
    }
}


这是一个Player模型:

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; }
}


知道我做错了什么吗?

最佳答案

确保在您的Web配置中,databaseInitializer元素指向IDatabaseInitializer(例如SchoolInitializer)而不是AZSContext

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

关于c# - 尝试播种数据库时出现EF异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27670302/

10-11 15:34