I tried to work with Code First approach in the new Entity Framework, but the table in the database is not automatically created.
I have already created database (in App_Code folder) and I use the Code First approach. Explain me, I need to create tables in DB first or they should be created automatically?
Below is a description of my project
In the Web.config I have 2 connection strings:
add name="ApplicationServices"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient"
add name="MyDB"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI; AttachDBFilename=|DataDirectory|MyDB.mdf;User Instance=true"
providerName="System.Data.SqlClient"
Class describing my object (in Model folder)
public class UserProfile
{
[Key]
[Required]
public string PhoneNumber { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string MiddleName { get; set; }
[Required]
public string Surname { get; set; }
[Required]
public DateTime Birthday { get; set; }
public int PositionId { get; set; }
public string Boss { get; set; }
[Required]
public int CompanyId { get; set; }
}
DbContext class (in Model folder)
public class MyDB : DbContext
{
//public MyDB() : base("MyDB") { }
public DbSet<UserProfile> UserProfiles { get; set; }
}
In the Controller trying to insert to the database new (& first) record (table not already exist).
UserProfile newProfile = new UserProfile();
newProfile.CompanyId = 1;
newProfile.PhoneNumber = model.PhoneNumber;
newProfile.FirstName = model.FirstName;
newProfile.MiddleName = model.MiddleName;
newProfile.Surname = model.Surname;
newProfile.Birthday = Convert.ToDateTime(model.Birthday);
var myDb = new Models.MyDB();
myDb.UserProfiles.Add(newProfile);
myDb.SaveChanges();
When I'm trying to call SaveChanges() I get an exception:
Exception Details: System.Data.SqlClient.SqlException: Invalid object name 'dbo.UserProfiles'.