开发环境
VS2017 + Win7 x64
生成操作数据库文件需要配置或添加的文件
1、Startup.cs
public IConfiguration Configuration { get; }
// 为了引入配置文件。默认的配置文件为"AppSettings.json"。
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
// 添加 Entity Framework 服务,并且使用SQL Server 服务。
services.AddEntityFrameworkSqlServer().
AddDbContext<WebDemoDbContext>(option => option.UseSqlServer(Configuration["database:connection"]));
// 设置获取 appsettions.json 里的值
services.Configure<AppsettingOptions>(Configuration);
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
// 调用wwwroot 里的文件
app.UseStaticFiles();
app.UseAuthentication();
// 默认首页
app.UseMvcWithDefaultRoute();
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
2、Program.cs
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.UseApplicationInsights()
.Build();
}
3、AppSettings.json
{
"database:connection": "Data Source=.;Initial Catalog=test;User ID=sa;Password=123"
}
Models 文件夹中
4、model 类
public class User
{
[Key]
public int Id { get; set; }
public string UserName{get;set;}
}
5、DbContext 类
public class WebDemoDbContext: DbContext
{
// 用户信息
public virtual DbSet<User> User{ get; set; }
public WebDemoDbContext(DbContextOptions<WebDemoDbContext> options) : base(options)
{
}
}
6、编辑解决方案
添加如下代码:
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
</ItemGroup>