0
点赞
收藏
分享

微信扫一扫

.Net Core MVC使用EF


新建项目:

.Net Core MVC使用EF_EF

.Net Core MVC使用EF_microsoft_02

 

添加EF:

执行连接语句

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

.Net Core MVC使用EF_EF_03

 

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

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

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

3.重启

生成如下文件:

.Net Core MVC使用EF_重启_04

修改文件:

CateDBContext.cs 中 将:

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=*****.;");
            }
        }

替换成:

public CateDBContext(DbContextOptions<CateDBContext> options)
            : base(options)
        {

        }

Startup.cs 中 将:

public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }

修改成:

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

 

使用EF,在控制器中:

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中使用:

.Net Core MVC使用EF_EF_05

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

 

.Net Core MVC使用EF_microsoft_06

 

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

net stop was /y

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 

.Net Core MVC使用EF_microsoft_07

举报

相关推荐

0 条评论