当前位置: 移动技术网 > IT编程>开发语言>.net > .NET Core整理之配置EFCore

.NET Core整理之配置EFCore

2019年01月23日  | 移动技术网IT编程  | 我要评论

安徽金寨,富甲西游网页版,医学在线

1、新建asp.net core web应用程序

2、从nuget下载安装以下工具包

     microsoft.entityframeworkcore

     microsoft.entityframeworkcore.sqlserver

     microsoft.entityframeworkcore.tools

     microsoft.entityframeworkcore.design

     microsoft.entityframeworkcore.sqlserver.design

3、然后,我们在vs的工具选项中,选择nuget包管理器,选择程序包管理控制台(其中models2是输出文件夹)

scaffold-dbcontext "server=.;database=test1;trusted_connection=true;" microsoft.entityframeworkcore.sqlserver -outputdir models

4、这里面就是你的上下文对象和相关的实体类了

 

5、注释上下文对象里的固化连接字符串

 

6、在配置文件里添加数据库连接字符串:

  "connectionstrings": { "sqlserver": "server=.;database=test;trusted_connection=true;" },

7、然后我们在startup中注入我们的上下文对象和获取数据库连接串

//注入上下文对象
services.adddbcontext<testcontext>(options =>
options.usesqlserver(configuration.getconnectionstring("sqlserver")));

 

8、创建控制器,代码如下

public class firstcontroller : controller
{
//构造函数注入上下文
private readonly testcontext _context;
public firstcontroller(testcontext context)
{
_context = context;
}

// get: /<controller>/
public iactionresult index(int? id)
{
base.viewdata["user1"] = new currentuser()
{
id = _context.testautoid.find(1).autoid1,
name = _context.testautoid.find(1).autoid2.tostring(),
account = _context.testautoid.find(1).autoid3.tostring(),
email = _context.testautoid.find(1).autoid4.tostring(),
password = _context.testautoid.find(1).autoid5.tostring(),

};

base.viewdata["something"] = 12345;

base.viewbag.name = "eleven";
base.viewbag.description = "teacher";
base.viewbag.user = new currentuser()
{
id = 7,
name = "ioc",
account = "限量版",
email = "莲花未开时",
password = "落单的候鸟",
logintime = datetime.now
};

base.tempdata["user"] = new currentuser()
{
id = 7,
name = "css",
account = "季雨林",
email = "koke",
password = "落单的候鸟",
logintime = datetime.now
};//后台可以跨action 基于session

if (id == null)
{
//return this.redirect("~/first/tempdatapage");//未完待续
//return this.re
return this.redirect("~/first/tempdatapage");
}

else
return view(new currentuser()
{
id = 7,
name = "一点半",
account = "季雨林",
email = "koke",
password = "落单的候鸟",
logintime = datetime.now
});
}

}

9、创建相应的视图如下:

@model netcore2._2.mvc6.models.currentuser
@using netcore2._2.mvc6.models;

@{
viewbag.title = "index";
currentuser userviewdata = viewdata["user1"] as currentuser;//viewdata需要类型转换
currentuser userviewbag = viewbag.user;//viewbag直接用
currentuser userother = viewbag.user1;
}

<div class="row">
<div class="col-md-4">
<h2>getting started</h2>
@base.model.name
<p>@(((currentuser)viewdata["user1"]).name)</p>
<p>@userviewdata.name</p>
<p>@userviewbag.account</p>
<p>@userother.name</p>
<p>@(((currentuser)viewbag.user).name)</p>
<p>@(((currentuser)tempdata["user"]).name)</p>
<p>@base.model.name</p>
</div>

</div>

10、然后在运行我们的代码.得到结果如下:

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网