Code First Entity Framework不会使用表

时间:2017-05-05 22:03:17

标签: c# asp.net entity-framework asp.net-mvc-4 webforms

我有几个模特(类)。

City.cs:

public class City
{
    [ScaffoldColumn(false)]
    public int CityID { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Course> Courses { get; set; }
}

Course.cs:

public class Course
{
    [ScaffoldColumn(false)]
    public int ID { get; set; }

    public string Faculty { get; set; }

    public int CityID { get; set; }
}

CourseDatabaseInitializer.cs:

using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;

namespace CoursesApplication.Models
{
    public class CourseDatabaseInitializer : DropCreateDatabaseAlways<CourseContext>
    {
        CourseContext _Context = new CourseContext();
        protected override void Seed(CourseContext context)
        {
            GetCities().ForEach(c => context.Cities.Add(c));
        }

        private static List<City> GetCities()
        {
            var cities = new List<City> {
                new City
                {
                    CityID = 1,
                    Name = "Paris"
                }
            };

            return cities;
        }

        public List<Course> GetCourses()
        {
            return (from c in _Context.Courses select c).ToList();
        }
    }
}

CourseContext.cs:

using System.Data.Entity;

namespace CoursesApplication.Models
{
    public class CourseContext : DbContext
    {
        public CourseContext(): base("CoursesApplication")
        {
        }

        public DbSet<Course> Courses { get; set; }
        public DbSet<City> Cities { get; set; }
    }
}

和我的Global.asax.cs文件:

void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);

        // Initialize the Courses database.
        Database.SetInitializer(new CourseDatabaseInitializer());
    }

,但是当我运行应用程序时,一切正常。之后在解决方案资源管理器中我创建了连接,但是没有带表的数据库。这是我的web.config连接字符串:

<add name="CourseContext"
    connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\courses.mdf;
Integrated Security=True"providerName="System.Data.SqlClient" />

哪里可以出问题? 我正在使用.NET Framework 4.6.1和Sql Express 2016。 这是ASP.NET WEB Forms项目。

1 个答案:

答案 0 :(得分:0)

CourseContext尝试更改此

public CourseContext(): base("CoursesApplication")
{
}

到这个

public CourseContext(): base("CourseContext")
{
}

或删除: base("CoursesApplication")