ASP.NET Core MVC+EF Core项目实战
项目背景
本项目参考于《Pro Entity Framework Core 2 for ASP.NET Core MVC》一书,项目内容为party邀请答复。
新建项目
本项目开发工具为VS2017,打开VS2017,新建项目,选择ASP.NETCore Web Application,项目名为PartyInvites,点击OK,选择模板为MVC(为了省事)。当然为了熟悉MVC流程也可以选择空模板自己来搭建项目结构。
项目开发
1.创建数据实体类以及数据库上下文类
在Models文件夹下创建两个类,DataContext和GuestResponse类,类中具体内容如下:
public class GuestResponse
{
public long Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public bool? WillAttend { get; set; }
}
public class DataContext : DbContext
{
public DataContext(DbContextOptions<DataContext> options) : base(options)
{ }
public DbSet<GuestResponse> Responses { get; set; }
}
2.编写Controller和View
打开Controllers文件夹下的HomeController文件(选择空模板的同学自己创建文件夹和HomeController文件),HomeController具体代码如下:
public class HomeController : Controller
{
private DataContext _dataContext;
public HomeController(DataContext dataContext) => _dataContext = dataContext;
public IActionResult Index() => View();
public IActionResult Respond() => View();
[HttpPost]
public IActionResult Respond(GuestResponse response)
{
_dataContext.Responses.Add(response);
_dataContext.SaveChanges();
return RedirectToAction(nameof(Thanks),
new { Name = response.Name, WillAttend = response.WillAttend });
}
public IActionResult Thanks(GuestResponse response)
{
return View(response);
}
public IActionResult ListResponses() =>
View(_dataContext.Responses.OrderByDescending(r => r.WillAttend));
}
修改Views/Shared文件夹下的_Layout.cshtml文件,如下:
<!DOCTYPE html> <html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Party Invites</title>
<link rel="stylesheet" href="/lib/bootstrap/dist/css/bootstrap.css" />
</head>
<body>
<div>
@RenderBody()
</div>
</body> </html>
在Home文件夹下,修改Index.cshtml,内容如下:
<div class="text-center m-4">
<h3>We're going to have an exciting party!</h3>
<h4>And you are invited</h4>
<a class="btn btn-primary" asp-action="Respond">RSVP Now</a>
</div>
创建新的cshtml文件,ListResponses.cshtml,
@model IEnumerable<GuestResponse>
<h3 class="bg-primary p-2 text-white text-center">
Here is the list of people who have
responded
</h3>
<div class="table-responsive">
<table class="table">
<tr>
<td>Name</td>
<td>Email</td>
<td>Phone</td>
<td>Attending</td>
</tr>
@foreach (GuestResponse r in Model)
{
<tr>
<td>@r.Name</td>
<td>@r.Email</td>
<td>@r.Phone</td>
<td>@(r.WillAttend == true ? "Yes" : "No")</td>
</tr> }
</table>
</div>
Respond.cshtml,
@model GuestResponse
<div class="bg-primary p-2 text-white text-center">
<h2>RSVP</h2>
</div>
<form asp-action="Respond" method="post" class="m-4">
<div class="form-group">
<label>Your Name</label>
<input asp-for="Name" class="form-control" />
</div>
<div class="form-group">
<label>Your Email</label>
<input asp-for="Email" class="form-control" />
</div>
<div class="form-group">
<label>Your Phone Number</label>
<input asp-for="Phone" class="form-control" />
</div>
<div class="form-group">
<label>Will You Attend?</label>
<select asp-for="WillAttend" class="form-control">
<option value="">Choose an option</option>
<option value="true">Yes, I'll be there</option>
<option value="false">No, I can't come</option>
</select>
</div>
<div class="text-center">
<button type="submit" class="btn btn-primary">Submit RSVP</button>
</div>
</form>
Thanks.cshtml
@model GuestResponse
<div class="text-center mt-3">
<h1>Thank you, @Model.Name!</h1>
@if (Model.WillAttend == true)
{
<div>
It's great that you're coming. The drinks are already in the fridge!
</div>
}
else
{
<div>
Sorry to hear that you can't make it, but thanks for letting us know.
</div>
}
Click <a asp-action="ListResponses">here</a> to see who is coming.
</div>
配置EF Core
配置数据库连接字符串,在appsettings.json文件中增加如下内容:
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=PartyInvites;Trusted_Connection=True;MultipleActiveResultSets=true"
}
DefaultConnection的内容为你自己的数据库连接字符串。
修改startup.cs内容,代码如图
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
} public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
//config database connect string
string conString = Configuration["ConnectionStrings:DefaultConnection"];
services.AddDbContext<DataContext>(options =>
options.UseSqlServer(conString));
} // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseDeveloperExceptionPage();
app.UseStatusCodePages();
app.UseStaticFiles();
//important
app.UseMvcWithDefaultRoute();
}
}
配置好后,根据新建的data Model,创建数据库,打开nuget 控制台,在控制台中输入add-migration加名字,如add-migration addData,执行,会自动建立migrations文件夹,并在文件夹中建立addData文件,意味创建迁移文件成功。然后输入:update-database,数据库就创建完成,可以去数据库检查下表建立是否成功。
然后就可以运行项目了。
需要注意的是,前段引用了bootstrap,需要注意bootstrap是否安装成功以及版本问题,否则页面可能显示不正确。
ASP.NET Core MVC+EF Core项目实战的更多相关文章
- ASP.NET Core MVC+EF Core从开发到部署
笔记本电脑装了双系统(Windows 10和Ubuntu16.04)快半年了,平时有时间就喜欢切换到Ubuntu系统下耍耍Linux,熟悉熟悉Linux命令.Shell脚本以及Linux下的各种应用的 ...
- 国产化之路-统信UOS + Nginx + Asp.Net MVC + EF Core 3.1 + 达梦DM8实现简单增删改查操作
专题目录 国产化之路-统信UOS操作系统安装 国产化之路-国产操作系统安装.net core 3.1 sdk 国产化之路-安装WEB服务器 国产化之路-安装达梦DM8数据库 国产化之路-统信UOS + ...
- 快读《ASP.NET Core技术内幕与项目实战》WebApi3.1:WebApi最佳实践
本节内容,涉及到6.1-6.6(P155-182),以WebApi说明为主.主要NuGet包:无 一.创建WebApi的最佳实践,综合了RPC和Restful两种风格的特点 1 //定义Person类 ...
- ASP.NET CORE MVC 2.0 项目中引用第三方DLL报错的解决办法 - InvalidOperationException: Cannot find compilation library location for package
目前在学习ASP.NET CORE MVC中,今天看到微软在ASP.NET CORE MVC 2.0中又恢复了允许开发人员引用第三方DLL程序集的功能,感到甚是高兴!于是我急忙写了个Demo想试试,我 ...
- 简读《ASP.NET Core技术内幕与项目实战》之3:配置
特别说明:1.本系列内容主要基于杨中科老师的书籍<ASP.NET Core技术内幕与项目实战>及配套的B站视频视频教程,同时会增加极少部分的小知识点2.本系列教程主要目的是提炼知识点,追求 ...
- 快读《ASP.NET Core技术内幕与项目实战》EFCore2.5:集合查询原理揭秘(IQueryable和IEnumerable)
本节内容,涉及4.6(P116-P130).主要NuGet包:如前述章节 一.LINQ和EFCore的集合查询扩展方法的区别 1.LINQ和EFCore中的集合查询扩展方法,虽然命名和使用完全一样,都 ...
- 《ASP.NET Core技术内幕与项目实战》精简集-目录
本系列是杨中科2022年最新作品<ASP.NET Core技术内幕与项目实战>及B站配套视频(强插点赞)的精简集,是一个读书笔记.总结和提炼了主要知识点,遵守代码优先原则,以利于快速复习和 ...
- 【ASP.NET Core】EF Core - “影子属性” 深入浅出经典面试题:从浏览器中输入URL到页面加载发生了什么 - Part 1
[ASP.NET Core]EF Core - “影子属性” 有朋友说老周近来博客更新较慢,确实有些慢,因为有些 bug 要研究,另外就是老周把部分内容转到直播上面,所以写博客的内容减少了一点. ...
- 开源题材征集 + MVC&EF Core 完整教程小结
到目前为止,我们的MVC+EF Core 完整教程的理论部分就全部结束了,共20篇,覆盖了核心的主要知识点. 下一阶段是实战部分,我们将会把这些知识点串联起来,用10篇(天)来完成一个开源项目. 现向 ...
随机推荐
- 文本查重算法SimHash
1.介绍 爬虫采集了大量的文本数据,如何进行去重?可以使用文本计算MD5,然后与已经抓取下来的MD5集合进行比较,但这种做法有个问题,文本稍有不同MD5值都会大相径庭, 无法处理文本相似问题.另一种方 ...
- Mybatis总结之如何自动生成数据库表结构
一般情况下,用Mybatis的时候是先设计表结构再进行实体类以及映射文件编写的,特别是用代码生成器的时候. 但有时候不想用代码生成器,也不想定义表结构,那怎么办? 这个时候就会想到Hibernate, ...
- JAVA eclipse 问题汇总(持续更新)
解决eclipse中文字很小 新下载的eclipse4.2.1版本,显示中文字体很小,但是英文比较正常.网上查看要更改字体大小,但是更改后英文也变大了,不是想要的结果.window – prefere ...
- 数据库系统(六)---MySQL语句及存储过程
一.DDL.DML.DCL常用语句 1.DDL(Data Definition Language)数据库定义语言 (1)数据库模式定义 #创建数据库 create database if exsite ...
- Unity3d粒子特效:制作火焰效果
效果 分析 真实的火焰效果,通常包括:火.火光.火星等组成部分,而火焰对周围环境的烘焙,可以通过灯光实现,如点光源. 针对火焰组成部分,我们可以创建对应的粒子系统组件,实现相应的效果,如下图所示: 1 ...
- 调试webpack
调试webpack 1. 摘要 用过构建工具webpack的朋友应该都体会,面对其几百行的配置内容如大海一小舟,找不到边.看文档查百度,对其构建的生命周期看了又看.最终还是很茫然.原因很简单,构建配置 ...
- 基于SkyWalking的分布式跟踪系统 - 异常告警
通过前面2篇文章我们搭建了SW的基础环境,监控了微服务,能了解所有服务的运行情况.但是当出现服务响应慢,接口耗时严重时我们需要立即定位到问题,这就需要我们今天的主角--监控告警,同时此篇也是SW系列的 ...
- 【XSY2558】圆上的蚂蚁 Ants on circle
Description L个点围成一个圆. 我们选定任意一个点作为原点, 则每个点的坐标为从原点顺时针走到这个点的距离. 圆上有N只蚂蚁, 分别被编号为1到N. 开始时, 第ii只蚂蚁在坐标为Xi的点 ...
- 熊海cms v1.0 完全代码审计
很久以前写的,写这个东西更多的是为了说明我自己的一个思路,即按照程序功能点进行代码审计, 这样经过一段时间训练,熟悉了某种功能的正确和错误实现方法,遇到类似的代码就可以很快看出是否有问题了 --- 0 ...
- 使用Typescript重构axios(十三)——让响应数据支持泛型
0. 系列文章 1.使用Typescript重构axios(一)--写在最前面 2.使用Typescript重构axios(二)--项目起手,跑通流程 3.使用Typescript重构axios(三) ...