ASP.NET Core MVC+EF Core项目实战

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 options) : base(options)
        {

        }
        public DbSet 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文件,如下:





    
    Party Invites
    


    
@RenderBody()

在Home文件夹下,修改Index.cshtml,内容如下:

We're going to have an exciting party!

And you are invited

RSVP Now

创建新的cshtml文件,ListResponses.cshtml,


@model IEnumerable

Here is the list of people who have responded

@foreach (GuestResponse r in Model) { }
Name Email Phone Attending
@r.Name @r.Email @r.Phone @(r.WillAttend == true ? "Yes" : "No")

Respond.cshtml,

@model GuestResponse

RSVP

Thanks.cshtml

@model GuestResponse

Thank you, @Model.Name!

@if (Model.WillAttend == true) {
It's great that you're coming. The drinks are already in the fridge!
} else {
Sorry to hear that you can't make it, but thanks for letting us know.
} Click here to see who is coming.

配置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(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是否安装成功以及版本问题,否则页面可能显示不正确。

项目源码:https://github.com/zfy1994/Test

你可能感兴趣的:(ASP.NET,Core)