新创建的MVC项目使用的都是内置的数据库
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-Gary-20170606113234.mdf;Initial Catalog=aspnet-Gary-20170606113234;Integrated Security=True"
providerName="System.Data.SqlClient" />
根据需要更换为SQLServer数据库,添加配置字符串:
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-Gary-20170606113234.mdf;Initial Catalog=aspnet-Gary-20170606113234;Integrated Security=True"
providerName="System.Data.SqlClient" />
<add name="GaryDBContext" connectionString="Data Source=127.0.0.1;Initial Catalog=GaryWeb;Integrated Security=True;User Id=sa;Password=123456"
providerName="System.Data.SqlClient" />
</connectionStrings>
在Context.cs类中使用该配置:
using System.Data.Entity;
namespace Gary.Core
{
/// <summary>
/// 数据上下文
/// GaryContext类是项目的数据数据上下文,使模型和数据库的表进行对应。
/// </summary>
public class GaryContext : DbContext
{
/// <summary>
/// 管理员集合
/// </summary>
public DbSet<Administrator> Administrators { get; set; }
public GaryContext() : base("GaryDBContext")
{
Database.SetInitializer(new CreateDatabaseIfNotExists<GaryContext>());
}
}
}
这样就完成啦!