iT邦幫忙

2017 iT 邦幫忙鐵人賽
DAY 1
0
Modern Web

Learning ASP.NET core + Angular2 系列 第 1

[ASP.NET Core] Build MVC website with Entity Framework Core

  • 分享至 

  • xImage
  •  

Introduction


Let's begin learning how to build a development environment for .NET Core applications and create a MVC website with Entity Framework Core and NLog.

Notice the frameworks and pakcages are moving very fast and the ones of mine may differ from yours.

Environment


  • Visual Studio 2015 Update 3
  • Visual Studio 2015 DotNetCore tools – preview 2
  • DotNetCore 1.0.0 Runtime

Downloads


Update Visual Studio

Visual Studio downloads

Install .NET Core SDK

Find it on Microsoft .NET Framework Downloads.

Install VS2015 DotNetCore tools – preview 2

Download it here.

Walk thru


Create ASP.NET Core website project

  • appsettings.json
    Most settings in WebConfig was moved to this file. We will later add connctionString into appsettings.json.

  • bundleconfig.json
    We can use gulp/ or Bundler & Minifier.

  • project.json
    project.json is the file which is for managing the packages and dependencies.
    We can still use NUGET to install the package, or just editing the project.json and use dotnet restore to restore or remove the packages for us.

NLog

Install NLog.Extensions.Logging
Reference : NLog/NLog.Extensions.Logging

Injection

Then inject the NLog provider into loggerFactory in Startup.cs : Configure

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    //add NLog to ASP.NET Core
    loggerFactory.AddNLog();
    //Configure nlog.config in your project root
    env.ConfigureNLog("NLog.config");
}

PS. Don’t forget to set NLog.config!

Usage

public class StoreController : Controller
{
    protected static Logger _logger = LogManager.GetCurrentClassLogger();
    public IActionResult Index()
    {
        _logger.Debug($"Debug message from current logger!");
        _logger.Error($"Error message from current logger!");
    }
}

Entity Framework Core (to Sql server)


Package : Microsoft.EntityFrameworkCore.SqlServer

ConnectionString

Create DbContext and DAO

  • DbContext
public class DefaultDbContext : DbContext
{
    public DefaultDbContext(DbContextOptions options) : base(options) 
    {}
    public DbSet<Store> Stores { get; set; }
}
  • DAO
[Table("Stores")]
public class Store
{
    [Key]
    public int Id { get; set; }
    [StringLength(200)]
    [Required]
    public string Name { get; set; }
    [StringLength(500)]
    public string Description { get; set; }
}

Injection

In this step, we will create DbContext and inject it to IServiceCollection.
In Startup.cs : ConfigureServices, add the following code.

public void ConfigureServices(IServiceCollection services)
{
   // Add Entity Framework
   services.AddDbContext<DefaultDbContext>(
                options => options.UseSqlServer(
                    Configuration["Data:DefaultConnection:ConnectionString"]));
}

Usage

Since we inject the EntityFrameworkCore.SqlServer provider, we can use the DbContext like this,

public class StoreController : Controller
{
    private DefaultDbContext _dbContext = null;
    public StoreController(DefaultDbContext dbContext)
    {
            this._dbContext = dbContext;
            //Do something with this._dbContext ... 
    }
}

Implement a Hello world


Okay, we have logger and ORM now. It’s time to implement a simple web page!

View

  • index.cshtml
@model  IEnumerable<JB.Sample.AspNetCore.DAL.Store>
<table class="list">
    <thead>
        <tr>
            <th>@Html.DisplayNameFor(model => Model.First().Id)</th>
            <th>@Html.DisplayNameFor(model => Model.First().Name)</th>
            <th>@Html.DisplayNameFor(model => Model.First().Description)</th>
        </tr>
    </thead>

    <tbody>
        @if (Model != null)
        {
            foreach (var item in Model)
            {
                <tr>
                    <td>@Html.DisplayFor(model => item.Id)</td>
                    <td>@Html.DisplayFor(model => item.Name)</td>
                    <td>@Html.DisplayFor(model => item.Description)</td>
                </tr>
            }
        }
    </tbody>
</table>

Controller

  • StoreController.cs
public IActionResult Index()
{
    using (var storeService = new StoreService(DbContextFactory.Create()))
    {
        var stores = storeService.GetAll();
        return View(stores);
    }
}
  • StoreService.cs
public class StoreService : IDisposable
{
        private DefaultDbContext _dbContext = null;
        public StoreService(DefaultDbContext dbContext)
        {
            if(dbContext!=null)
            {
                this._dbContext = dbContext;
            }
        }

        public IEnumerable<Store> GetAll()
        {
            return this._dbContext.Stores;
        }
}

Result

Tag Helpers


There is another new feature of ASP.NET Core MVC 6 – Tag Helpers.
Tag Helpers ain’t created to replace Html Helpers, but enhance them.

For more details, take a look at
Tag Helpers in ASP.NET MVC 6 - An Overview
Cleaner Forms using Tag Helpers in ASP.NET Core MVC

Reference


  1. Microsoft ASP.NET Core Documentation
  2. Microsoft Entity Framework Core document
  3. GitHub : aspnet/Docs

下一篇
[ASP.NET Core] Set Routing
系列文
Learning ASP.NET core + Angular2 31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言