Tuesday, October 11, 2016

Fully Working Code Sample: ASP.NET MVC Core 1.1, Entity Framework Core, Database First (4) - Views

Index.cshtml


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
@model IEnumerable<CASAPOC.Entities.TongTestPerson>

@{
    ViewBag.Title = "Test Persons";
}

<h2>Persons</h2>

<p>
    <a asp-controller="Person" asp-action="Create">Create New</a>
</p>

<table class="table">
    <tr>
        <th>First Name</th>
        <th>Last Name</th>
    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.FirstName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.LastName)
            </td>
            <td>
                <a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
                <a asp-action="Details" asp-route-id="@item.Id">Details</a> |
                <a asp-action="Delete" asp-route-id="@item.Id">Delete</a>
            </td>
        </tr>
    }
</table>


Create.cshtml:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
@model CASAPOC.Entities.TongTestPerson

@{
    ViewBag.Title = "New Person";
}

<h2>@ViewData["Title"]</h2>

<form asp-controller="Person" asp-action="Create" method="post" class="form-horizontal" role="form">
    <div class="form-horizontal">
        <div asp-validation-summary="All" class="text-danger"></div>
        <div class="form-group">
            <label asp-for="FirstName" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <input asp-for="FirstName" class="form-control" />
                <span asp-validation-for="FirstName" class="text-danger"></span>
            </div>
            <label asp-for="LastName" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <input asp-for="LastName" class="form-control" />
                <span asp-validation-for="LastName" class="text-danger"></span>
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
</form>


Details.cshtml:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
@model CASAPOC.Entities.TongTestPerson

@{
    ViewData["Title"] = "View";
}

<h2>View</h2>

<div>
    <h4>TongTestPerson</h4>
    <hr />
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => model.FirstName)
        </dt>
        <dd>
            @Html.DisplayFor(model => model.FirstName)
        </dd>
        <dt>
            @Html.DisplayNameFor(model => model.LastName)
        </dt>
        <dd>
            @Html.DisplayFor(model => model.LastName)
        </dd>
    </dl>
</div>
<div>
    <a asp-action="Edit" asp-route-id="@Model.Id">Edit</a> |
    <a asp-action="Index">Back to List</a>
</div>


Edit.cshtml:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
@model CASAPOC.Entities.TongTestPerson

@{
    ViewData["Title"] = "Edit";
}

<h2>Edit</h2>

<form asp-action="Edit">
    <div class="form-horizontal">
        <h4>TongTestPerson</h4>
        <hr />
        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
    <input type="hidden" asp-for="Id" />
        <div class="form-group">
            <label asp-for="FirstName" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <input asp-for="FirstName" class="form-control" />
                <span asp-validation-for="FirstName" class="text-danger" />
            </div>
        </div>
        <div class="form-group">
            <label asp-for="LastName" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <input asp-for="LastName" class="form-control" />
                <span asp-validation-for="LastName" class="text-danger" />
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </div>
    </div>
</form>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}


Delete.cshtml:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
@model CASAPOC.Entities.TongTestPerson

@{
    ViewData["Title"] = "Delete";
}

<h2>Delete</h2>

<h3>Are you sure you want to delete this?</h3>
<div>
    <h4>TongTestPerson</h4>
    <hr />
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => model.FirstName)
        </dt>
        <dd>
            @Html.DisplayFor(model => model.FirstName)
        </dd>
        <dt>
            @Html.DisplayNameFor(model => model.LastName)
        </dt>
        <dd>
            @Html.DisplayFor(model => model.LastName)
        </dd>
    </dl>
   
    <form asp-action="Delete">
        <div class="form-actions no-color">
            <input type="submit" value="Delete" class="btn btn-default" /> |
            <a asp-action="Index">Back to List</a>
        </div>
    </form>
</div>

Fully Working Code Sample: ASP.NET MVC Core 1.1, Entity Framework Core, Database First (3) - Controller


  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
using CASAPOC.Entities;
using Microsoft.AspNetCore.Mvc;
using System.Linq;

namespace CASAPOC.Controllers
{
    public class PersonController : Controller
    {
        private readonly KCMSContext _context;

        public PersonController(KCMSContext context)
        {
            _context = context;
        }

        public IActionResult Index()
        {
            return View(_context.TongTestPerson.ToList());
        }

        public IActionResult Create()
        {

            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Create(TongTestPerson person)
        {
            if (ModelState.IsValid)
            {
                _context.TongTestPerson.Add(person);
                _context.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(person);
        }

        // GET: Person/Details/5
        public IActionResult Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var person = _context.TongTestPerson.SingleOrDefault(m => m.Id == id);
            if (person == null)
            {
                return NotFound();
            }

            return View(person);
        }

        // GET: Movies/Edit/5
        public IActionResult Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var person = _context.TongTestPerson.SingleOrDefault(m => m.Id == id);
            if (person == null)
            {
                return NotFound();
            }
            return View(person);
        }

        // POST: Movies/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Edit(int id, [Bind("Id, FirstName, LastName")] TongTestPerson person)
        {
            if (id != person.Id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(person);
                    _context.SaveChanges();
                }
                catch (System.Exception e)
                {
                    if (!PersonExists(person.Id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction("Index");
            }
            return View(person);
        }

        // GET: Person/Delete/5
        public IActionResult Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var person = _context.TongTestPerson.SingleOrDefault(m => m.Id == id);
            if (person == null)
            {
                return NotFound();
            }

            return View(person);
        }

        // POST: Person/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public IActionResult DeleteConfirmed(int id)
        {
            var person = _context.TongTestPerson.SingleOrDefault(m => m.Id == id);
            _context.TongTestPerson.Remove(person);
            _context.SaveChanges();
            return RedirectToAction("Index");
        }

        private bool PersonExists(int id)
        {
            return _context.TongTestPerson.Any(e => e.Id == id);
        }
    }
}

Fully Working Code Sample: ASP.NET MVC Core 1.1, Entity Framework Core, Database First (2)

1) Open KCMSContext.cs file under Entities folder,

replace


1
2
3
4
5
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            #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=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;");
        }



with


1
2
3
        public KCMSContext(DbContextOptions<KCMSContext> options)
            : base(options)
        { }


2) Open startup.cs, in the method: public void ConfigureServices(IServiceCollection services)


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
        public void ConfigureServices(IServiceCollection services)
        {
            var connection = @"Data Source=CTSCKVCMSSQLTst;Initial Catalog=KCMS2_Migration;Integrated Security=True;Persist Security Info=True;MultipleActiveResultSets=True;";
            services.AddDbContext<KCMSContext>(options => options.UseSqlServer(connection));

            // Add framework services.
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            services.AddMvc();

            // Add application services.
            services.AddTransient<IEmailSender, AuthMessageSender>();
            services.AddTransient<ISmsSender, AuthMessageSender>();
        }




Fully Working Code Sample: ASP.NET MVC Core 1.1, Entity Framework Core, Database First (1)

1) First things first, you need installed the following things:

Visual Studio 2015 Update 3
.NET Core for Visual Studio


2) Open VS2015, create a new project called CASAPOC, this is an
ASP.NET Core Web Application (.NET Core)

3) Install Entity Framework 


To use EF Core, install the package for the database provider(s) you want to target. We are using MS SQL server

in VS2015, Tools ‣ NuGet Package Manager ‣ Package Manager Console

run Install-Package Microsoft.EntityFrameworkCore.SqlServer
run Install-Package Microsoft.EntityFrameworkCore.Tools –Pre  
run Install-Package Microsoft.EntityFrameworkCore.SqlServer.Design 

find the project.json, and open it, under the "tools" section, you will find the snippet like this:

    "Microsoft.AspNetCore.Razor.Tools": "1.0.0-preview2-final",
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final",
    "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final",


4) Supposed that we have a database table called TongTestPerson
creation script:

USE [KCMS2_Migration]
GO

/****** Object:  Table [dbo].[TongTestPerson]    Script Date: 10/11/2016 1:01:19 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[TongTestPerson](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [FirstName] [varchar](50) NULL,
    [LastName] [varchar](50) NULL,
 CONSTRAINT [PK_TongTestPerson] PRIMARY KEY CLUSTERED
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO



5) Find out the database connection string, something like


Data Source=CTSCKVCMSSQLTst;Initial Catalog=KCMS2_Migration;Integrated Security=True;Persist Security Info=True;MultipleActiveResultSets=True

6) in VS2015, Tools ‣ NuGet Package Manager ‣ Package Manager Console

run 

Scaffold-DbContext "Data Source=CTSCKVCMSSQLTst;Initial Catalog=KCMS2_Migration;Integrated Security=True;Persist Security Info=True;MultipleActiveResultSets=True" Microsoft.EntityFrameworkCore.SqlServer -outputDir  Entities -context KCMSContext -force -DataAnnotations


this will create the Entity classes and DbContext classes from the existing database KCMS2_Migration

Blog Archive