深度优先

这个家伙好懒,除了文章什么都没留下

0%

【.Net Core】MVC使用EF

新建项目:

添加EF:

执行连接语句

1
Scaffold-DbContext "Server=120.79.***.238;Database=CateDB;uid=sa;pwd=*****.;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir DAL

注:执行这一步的时候出现了点问题 ,因为系统是win7,powershell版本太低了,不支持这个命令,需要安装3.0以上的powershell版本才行

1.Download from http://www.microsoft.com/en-us/download/details.aspx?id=34595

  1. 安装Windows Management Framework 3.0的6.1内核版本安装文件(Windows6.1-KB2506143-x64.msu)。

3.重启

生成如下文件:

修改文件:

CateDBContext.cs 中 将:

1
2
3
4
5
6
7
8
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
optionsBuilder.UseSqlServer(@"Server=*****;Database=CateDB;uid=sa;pwd=*****.;");
}
}

替换成:

1
2
3
4
5
    public CateDBContext(DbContextOptions<CateDBContext> options)
            : base(options)
{

}

Startup.cs 中 将:

1
2
3
4
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}

修改成:

1
2
3
4
5
6
7
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<CateDBContext>(option => {
option.UseSqlServer(@"server=******;Database=CMDB;uid=sa;pwd=***.;");
});
services.AddMvc();
}

使用EF,在控制器中:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
private CateDBContext _context;
public HomeController(CateDBContext context)
{
_context = context;
}

/// <summary>
/// 查询
/// </summary>
/// <returns></returns>
public IActionResult Index()
{
var data = _context.Users.ToList();
return View();
}

其他操作的和在asp.net 里操作ef差不多,在Entity Framework Core (EF Core)有许多新的功能,最令人期待的功能之一就是批处理语句。后面再学学。

View中使用:

顺便提下,发布到IIS遇到的问题:

在windows server 2012 上安装完dotnet-win-x64.1.1.1.exe 和 DotNetCore.1.0.4_1.1.1-WindowsHosting.exe后,没有重启服务器,访问站点报以上错误,解决办法要么重启,要么执行以下两条命令:

1
net stop was /y
1
net start w3svc

下载地址:https://download.microsoft.com/download/3/7/1/37189942-C91D-46E9-907B-CF2B2DE584C7/dotnet-sdk-2.1.200-win-x64.exe

https://download.microsoft.com/download/9/1/7/917308D9-6C92-4DA5-B4B1-B4A19451E2D2/dotnet-hosting-2.1.0-win.exe