简体   繁体   中英

Entity Framework creating database with no tables in it

I'm creating an ASP.NET MVC web application. I've installed the Entity Framework. I have done the following model:

public class EmploymentHistory
{
    public Guid Id { get; set; }
    public Guid UserId { get; set; }
    public int DateFromMonth { get; set; }
    public int DateFromYear { get; set; }
    public int DateToMonth { get; set; }
    public int DateToYear { get; set; }
    public string CompanyName { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Zip { get; set; }
    public string County { get; set; }
    [DisplayName("I was unemployed during this time")]
    public bool IsUnemployed { get; set; }
}

I have created the following DbContext class:

public class EmploymentDbContext : DbContext
{
    public DbSet<EmploymentHistory> EmploymentsHistory { get; set; }
}

And the connection string in my Web.config file looks like that:

<connectionStrings>
<add name="EmploymentDbContext" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=EmploymentsHistory;Integrated Security=False" providerName="System.Data.SqlClient"/>
</connectionStrings>

When I run the project, I can see the database EmploymentsHistory in the Server Explorer in Visual Studio but when I expand it and then expand its Tables, I can't see the EmploymentHistory table which I'm supposed to see.

Try adding a constructor to your EmploymentDbContext class, so it would be like this:

public class EmploymentDbContext : DbContext
{
    // constructor, which will also call DbContext's (base) constructor
    public EmploymentDbContext() : base("name=EmploymentDbContext") { } 

    public DbSet<EmploymentHistory> EmploymentsHistory { get; set; }
}

By calling DbContext 's constructor, you're specifying the name of the connection string you'd like this subclass of DbContext to attach to.

Edit:

Since you don't seem to be trying to use this connection anywhere currently, try explicitly adding a code-first migration. If you haven't already, run enable-migrations in your Package Manager Console. Close out of the Configuration screen it presents, and then run add-migration EmploymentHistory . Wait until it's finished, then run update-database and see if that fixes it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM