Lambda Expressions


The reference documents (https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/query-syntax-and-method-syntax-in-linq) states as follows:
Most queries in the introductory Language Integrated Query (LINQ) documentation are written by using the LINQ declarative query syntax. However, the query syntax must be translated into method calls for the .NET common language runtime (CLR) when the code is compiled. These method calls invoke the standard query operators, which have names such as Where, Select, GroupBy, Join, Max, and Average. You can call them directly by using method syntax instead of query syntax.

Convert Array into IEnumerable

Note

Notes

Convert Array into IEnumerable

The following example shows a simple query expression and the semantically equivalent query written as a method-based query.

C#
class QueryVMethodSyntax
{
static void Main()
{
int[] numbers = { 5, 10, 8, 3, 6, 12};

//Query syntax:
IEnumerable<int> numQuery1 =
from num in numbers
where num % 2 == 0
orderby num
select num;

//Method syntax:
IEnumerable<int> numQuery2 = numbers.Where(num => num % 2 == 0).OrderBy(n => n);

foreach (int i in numQuery1)
{
Console.Write(i + " ");
}
Console.WriteLine(System.Environment.NewLine);
foreach (int i in numQuery2)
{
Console.Write(i + " ");
}

// Keep the console open in debug mode.
Console.WriteLine(System.Environment.NewLine);
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
}
/*
Output:
6 8 10 12
6 8 10 12
*/




Create an in-Memory Data Source

Note

Notes

Create an in-Memory Data Source

The data source for the queries is a simple list of Student objects. Each Student record has a first name, last name, and an array of integers that represents their test scores in the class. Copy this code into your project. Note the following characteristics:
The Student class consists of auto-implemented properties.
Each student in the list is initialized with an object initializer.
The list itself is initialized with a collection initializer.
This whole data structure will be initialized and instantiated without explicit calls to any constructor or explicit member access. For more information about these new features, see Auto-Implemented Properties (C# Programming Guide) and Object and Collection Initializers (C# Programming Guide).

To add the data source

Note

Notes

To add the data source

Add the Student class and the initialized list of students to the Program class in your project.

public class Student
{
public string First { get; set; }
public string Last { get; set; }
public int ID { get; set; }
public List<int> Scores;
}

// Create a data source by using a collection initializer.
static List<Student> students = new List<Student>
{
new Student {First="Svetlana", Last="Omelchenko", ID=111, Scores= new List<int> {97, 92, 81, 60}},
new Student {First="Claire", Last="O'Donnell", ID=112, Scores= new List<int> {75, 84, 91, 39}},
new Student {First="Sven", Last="Mortensen", ID=113, Scores= new List<int> {88, 94, 65, 91}},
new Student {First="Cesar", Last="Garcia", ID=114, Scores= new List<int> {97, 89, 85, 82}},
new Student {First="Debra", Last="Garcia", ID=115, Scores= new List<int> {35, 72, 91, 70}},
new Student {First="Fadi", Last="Fakhouri", ID=116, Scores= new List<int> {99, 86, 90, 94}},
new Student {First="Hanying", Last="Feng", ID=117, Scores= new List<int> {93, 92, 80, 87}},
new Student {First="Hugo", Last="Garcia", ID=118, Scores= new List<int> {92, 90, 83, 78}},
new Student {First="Lance", Last="Tucker", ID=119, Scores= new List<int> {68, 79, 88, 92}},
new Student {First="Terry", Last="Adams", ID=120, Scores= new List<int> {99, 82, 81, 79}},
new Student {First="Eugene", Last="Zabokritski", ID=121, Scores= new List<int> {96, 85, 91, 60}},
new Student {First="Michael", Last="Tucker", ID=122, Scores= new List<int> {94, 92, 91, 91} }
};




Create the query

Note

Notes

Create the query


Build a query to list the Students with scores > 90


// The first line could also be written as "var studentQuery ="
IEnumerable<Student> studentQuery =
from student in students
where student.Scores[0] > 90
select student;




To execute the query

Note

Notes

To execute the query

Now write the foreach loop that will cause the query to execute. Note the following about the code:
Each element in the returned sequence is accessed through the iteration variable in the foreach loop.
The type of this variable is Student, and the type of the query variable is compatible, IEnumerable<Student>.
After you have added this code, build and run the application by pressing Ctrl + F5 to see the results in the Console window.


Execute the query

Note

Notes

Execute the query


// var could be used here also.
foreach (Student student in studentQuery)
{
Console.WriteLine("{0}, {1}", student.Last, student.First);
}

// Output:
// Omelchenko, Svetlana
// Garcia, Cesar
// Fakhouri, Fadi
// Feng, Hanying
// Garcia, Hugo
// Adams, Terry
// Zabokritski, Eugene
// Tucker, Michael



To add another filter condition

Note

Notes

To add another filter condition

You can combine multiple Boolean conditions in the where clause in order to further refine a query. The following code adds a condition so that the query returns those students whose first score was over 90 and whose last score was less than 80. The where clause should resemble the following code.
where student.Scores[0] > 90 && student.Scores[3] < 80


To order the results

Note

Notes

To order the results

It will be easier to scan the results if they are in some kind of order. You can order the returned sequence by any accessible field in the source elements. For example, the following orderby clause orders the results in alphabetical order from A to Z according to the last name of each student. Add the following orderby clause to your query, right after the where statement and before the select statement:
orderby student.Last ascending
Now change the orderby clause so that it orders the results in reverse order according to the score on the first test, from the highest score to the lowest score.
orderby student.Scores[0] descending

Change the WriteLine format string so that you can see the scores:
Console.WriteLine("{0}, {1} {2}", student.Last, student.First, student.Scores[0]);


To group the results

Note

Notes

To group the results

Grouping is a powerful capability in query expressions. A query with a group clause produces a sequence of groups, and each group itself contains a Key and a sequence that consists of all the members of that group. The following new query groups the students by using the first letter of their last name as the key.

// studentQuery2 is an IEnumerable<IGrouping<char, Student>>
var studentQuery2 =
from student in students
group student by student.Last[0];


Note that the type of the query has now changed. It now produces a sequence of groups that have a char type as a key, and a sequence of Student objects. Because the type of the query has changed, the following code changes the foreach execution loop also:

// studentGroup is a IGrouping<char, Student>
foreach (var studentGroup in studentQuery2)
{
Console.WriteLine(studentGroup.Key);
foreach (Student student in studentGroup)
{
Console.WriteLine(" {0}, {1}",
student.Last, student.First);
}
}

// Output:
// O
// Omelchenko, Svetlana
// O'Donnell, Claire
// M
// Mortensen, Sven
// G
// Garcia, Cesar
// Garcia, Debra
// Garcia, Hugo
// F
// Fakhouri, Fadi
// Feng, Hanying
// T
// Tucker, Lance
// Tucker, Michael
// A
// Adams, Terry
// Z
// Zabokritski, Eugene



To order the groups by their key value

Note

Notes

To order the groups by their key value

When you run the previous query, you notice that the groups are not in alphabetical order. To change this, you must provide an orderby clause after the group clause. But to use an orderby clause, you first need an identifier that serves as a reference to the groups created by the group clause. You provide the identifier by using the into keyword, as follows:

var studentQuery4 =
from student in students
group student by student.Last[0] into studentGroup
orderby studentGroup.Key
select studentGroup;

foreach (var groupOfStudents in studentQuery4)
{
Console.WriteLine(groupOfStudents.Key);
foreach (var student in groupOfStudents)
{
Console.WriteLine(" {0}, {1}",
student.Last, student.First);
}
}

// Output:
//A
// Adams, Terry
//F
// Fakhouri, Fadi
// Feng, Hanying
//G
// Garcia, Cesar
// Garcia, Debra
// Garcia, Hugo
//M
// Mortensen, Sven
//O
// Omelchenko, Svetlana
// O'Donnell, Claire
//T
// Tucker, Lance
// Tucker, Michael
//Z
// Zabokritski, Eugene



To introduce an identifier by using let

Note

Notes

To introduce an identifier by using let

You can use the let keyword to introduce an identifier for any expression result in the query expression. This identifier can be a convenience, as in the following example, or it can enhance performance by storing the results of an expression so that it does not have to be calculated multiple times.

// studentQuery5 is an IEnumerable<string>
// This query returns those students whose
// first test score was higher than their
// average score.
var studentQuery5 =
from student in students
let totalScore = student.Scores[0] + student.Scores[1] +
student.Scores[2] + student.Scores[3]
where totalScore / 4 < student.Scores[0]
select student.Last + " " + student.First;

foreach (string s in studentQuery5)
{
Console.WriteLine(s);
}

// Output:
// Omelchenko Svetlana
// O'Donnell Claire
// Mortensen Sven
// Garcia Cesar
// Fakhouri Fadi
// Feng Hanying
// Garcia Hugo
// Adams Terry
// Zabokritski Eugene
// Tucker Michael


When you run this query, you will see the groups are now sorted in alphabetical order.

To use method syntax in a query expression

Note

Notes

To use method syntax in a query expression

As described in Query Syntax and Method Syntax in LINQ (C#), some query operations can only be expressed by using method syntax. The following code calculates the total score for each Student in the source sequence, and then calls the Average() method on the results of that query to calculate the average score of the class. Note the placement of parentheses around the query expression.

var studentQuery6 =
from student in students
let totalScore = student.Scores[0] + student.Scores[1] +
student.Scores[2] + student.Scores[3]
select totalScore;

double averageScore = studentQuery6.Average();
Console.WriteLine("Class average score = {0}", averageScore);

// Output:
// Class average score = 334.166666666667



To transform or project in the select clause

Note

Notes

To transform or project in the select clause

It is very common for a query to produce a sequence whose elements differ from the elements in the source sequences. Delete or comment out your previous query and execution loop, and replace it with the following code. Note that the query returns a sequence of strings (not Students), and this fact is reflected in the foreach loop.

IEnumerable<string> studentQuery7 =
from student in students
where student.Last == "Garcia"
select student.First;

Console.WriteLine("The Garcias in the class are:");
foreach (string s in studentQuery7)
{
Console.WriteLine(s);
}

// Output:
// The Garcias in the class are:
// Cesar
// Debra
// Hugo


Code earlier in this walkthrough indicated that the average class score is approximately 334. To produce a sequence of Students whose total score is greater than the class average, together with their Student ID, you can use an anonymous type in the select statement:

var studentQuery8 =
from student in students
let x = student.Scores[0] + student.Scores[1] +
student.Scores[2] + student.Scores[3]
where x > averageScore
select new { id = student.ID, score = x };

foreach (var item in studentQuery8)
{
Console.WriteLine("Student ID: {0}, Score: {1}", item.id, item.score);
}

// Output:
// Student ID: 113, Score: 338
// Student ID: 114, Score: 353
// Student ID: 116, Score: 369
// Student ID: 117, Score: 352
// Student ID: 118, Score: 343
// Student ID: 120, Score: 341
// Student ID: 122, Score: 368



Perform Left Outer Joins

Note

Notes

Perform Left Outer Joins


A left outer join is a join in which each element of the first collection is returned, regardless of whether it has any correlated elements in the second collection. You can use LINQ to perform a left outer join by calling the DefaultIfEmpty<TSource> method on the results of a group join.
Example
The following example demonstrates how to use the DefaultIfEmpty<TSource> method on the results of a group join to perform a left outer join.
The first step in producing a left outer join of two collections is to perform an inner join by using a group join. (See How to: Perform Inner Joins (C# Programming Guide) for an explanation of this process.) In this example, the list of Person objects is inner-joined to the list of Pet objects based on a Person object that matches Pet.Owner.
The second step is to include each element of the first (left) collection in the result set even if that element has no matches in the right collection. This is accomplished by calling DefaultIfEmpty<TSource> on each sequence of matching elements from the group join. In this example, DefaultIfEmpty<TSource> is called on each sequence of matching Pet objects. The method returns a collection that contains a single, default value if the sequence of matching Pet objects is empty for any Person object, thereby ensuring that each Person object is represented in the result collection.
The default value for a reference type is null; therefore, the example checks for a null reference before accessing each element of each Pet collection


class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}

class Pet
{
public string Name { get; set; }
public Person Owner { get; set; }
}

public static void LeftOuterJoinExample()
{
Person magnus = new Person { FirstName = "Magnus", LastName = "Hedlund" };
Person terry = new Person { FirstName = "Terry", LastName = "Adams" };
Person charlotte = new Person { FirstName = "Charlotte", LastName = "Weiss" };
Person arlene = new Person { FirstName = "Arlene", LastName = "Huff" };

Pet barley = new Pet { Name = "Barley", Owner = terry };
Pet boots = new Pet { Name = "Boots", Owner = terry };
Pet whiskers = new Pet { Name = "Whiskers", Owner = charlotte };
Pet bluemoon = new Pet { Name = "Blue Moon", Owner = terry };
Pet daisy = new Pet { Name = "Daisy", Owner = magnus };

// Create two lists.
List<Person> people = new List<Person> { magnus, terry, charlotte, arlene };
List<Pet> pets = new List<Pet> { barley, boots, whiskers, bluemoon, daisy };

var query = from person in people
join pet in pets on person equals pet.Owner into gj
from subpet in gj.DefaultIfEmpty()
select new { person.FirstName, PetName = (subpet == null ? String.Empty : subpet.Name) };

foreach (var v in query)
{
Console.WriteLine("{0,-15}{1}", v.FirstName + ":", v.PetName);
}
}

// This code produces the following output:
//
// Magnus: Daisy
// Terry: Barley
// Terry: Boots
// Terry: Blue Moon
// Charlotte: Whiskers
// Arlene:




Creating a Custom CopyToDataTable<T> Method

Note

Notes

Creating a Custom CopyToDataTable<T> Method

The existing CopyToDataTable methods only operate on an IEnumerable<T> source where the generic parameter T is of type DataRow. Although this is useful, it does not allow tables to be created from a sequence of scalar types, from queries that return anonymous types, or from queries that perform table joins. For an example of how to implement two custom CopyToDataTable methods that load a table from a sequence of scalar or anonymous types, see How to: Implement CopyToDataTable<T> Where the Generic Type T Is Not a DataRows.
The examples in this section use the following custom types:

public class Item
{
public int Id { get; set; }
public double Price { get; set; }
public string Genre { get; set; }
}

public class Book : Item
{
public string Author { get; set; }
}

public class Movie : Item
{
public string Director { get; set; }
}

Example
This example performs a join over the SalesOrderHeader and SalesOrderDetail tables to get online orders from the month of August and creates a table from the query.

// Fill the DataSet.
DataSet ds = new DataSet();
ds.Locale = CultureInfo.InvariantCulture;
FillDataSet(ds);

DataTable orders = ds.Tables["SalesOrderHeader"];
DataTable details = ds.Tables["SalesOrderDetail"];

var query =
from order in orders.AsEnumerable()
join detail in details.AsEnumerable()
on order.Field<int>("SalesOrderID") equals
detail.Field<int>("SalesOrderID")
where order.Field<bool>("OnlineOrderFlag") == true
&& order.Field<DateTime>("OrderDate").Month == 8
select new
{
SalesOrderID =
order.Field<int>("SalesOrderID"),
SalesOrderDetailID =
detail.Field<int>("SalesOrderDetailID"),
OrderDate =
order.Field<DateTime>("OrderDate"),
ProductID =
detail.Field<int>("ProductID")
};

DataTable orderTable = query.CopyToDataTable();


Example
The following example queries a collection for items of price greater than $9.99 and creates a table from the query results.

// Create a sequence.
Item[] items = new Item[]
{ new Book{Id = 1, Price = 13.50, Genre = "Comedy", Author = "Gustavo Achong"},
new Book{Id = 2, Price = 8.50, Genre = "Drama", Author = "Jessie Zeng"},
new Movie{Id = 1, Price = 22.99, Genre = "Comedy", Director = "Marissa Barnes"},
new Movie{Id = 1, Price = 13.40, Genre = "Action", Director = "Emmanuel Fernandez"}};

// Query for items with price greater than 9.99.
var query = from i in items
where i.Price > 9.99
orderby i.Price
select i;

// Load the query results into new DataTable.
DataTable table = query.CopyToDataTable();


Example
The following example queries a collection for items of price greater than 9.99 and projects the results. The returned sequence of anonymous types is loaded into an existing table.

// Create a sequence.
Item[] items = new Item[]
{ new Book{Id = 1, Price = 13.50, Genre = "Comedy", Author = "Gustavo Achong"},
new Book{Id = 2, Price = 8.50, Genre = "Drama", Author = "Jessie Zeng"},
new Movie{Id = 1, Price = 22.99, Genre = "Comedy", Director = "Marissa Barnes"},
new Movie{Id = 1, Price = 13.40, Genre = "Action", Director = "Emmanuel Fernandez"}};

// Create a table with a schema that matches that of the query results.
DataTable table = new DataTable();
table.Columns.Add("Price", typeof(int));
table.Columns.Add("Genre", typeof(string));

var query = from i in items
where i.Price > 9.99
orderby i.Price
select new { i.Price, i.Genre };

query.CopyToDataTable(table, LoadOption.PreserveChanges);


Example
The following example queries a collection for items of price greater than $9.99 and projects the results. The returned sequence of anonymous types is loaded into an existing table. The table schema is automatically expanded because the Book and Movies types are derived from the Item type.

// Create a sequence.
Item[] items = new Item[]
{ new Book{Id = 1, Price = 13.50, Genre = "Comedy", Author = "Gustavo Achong"},
new Book{Id = 2, Price = 8.50, Genre = "Drama", Author = "Jessie Zeng"},
new Movie{Id = 1, Price = 22.99, Genre = "Comedy", Director = "Marissa Barnes"},
new Movie{Id = 1, Price = 13.40, Genre = "Action", Director = "Emmanuel Fernandez"}};

// Load into an existing DataTable, expand the schema and
// autogenerate a new Id.
DataTable table = new DataTable();
DataColumn dc = table.Columns.Add("NewId", typeof(int));
dc.AutoIncrement = true;
table.Columns.Add("ExtraColumn", typeof(string));

var query = from i in items
where i.Price > 9.99
orderby i.Price
select new { i.Price, i.Genre };

query.CopyToDataTable(table, LoadOption.PreserveChanges);


Example

The following example queries a collection for items of price greater than $9.99 and returns a sequence of Double, which is loaded into a new table.
// Create a sequence.
Item[] items = new Item[]
{ new Book{Id = 1, Price = 13.50, Genre = "Comedy", Author = "Gustavo Achong"},
new Book{Id = 2, Price = 8.50, Genre = "Drama", Author = "Jessie Zeng"},
new Movie{Id = 1, Price = 22.99, Genre = "Comedy", Director = "Marissa Barnes"},
new Movie{Id = 1, Price = 13.40, Genre = "Action", Director = "Emmanuel Fernandez"}};

// load sequence of scalars.
IEnumerable<double> query = from i in items
where i.Price > 9.99
orderby i.Price
select i.Price;

DataTable table = query.CopyToDataTable();



Updating an MVC Partial View with Ajax

Note

Notes

Updating an MVC Partial View with Ajax

Partial views allow you to update only a part of the DOM without having to perform a full page refresh or a postback. In this example, we will create a master page that contains a drop-down box and then we will add a partial view to display data filtered by the drop-down value.

1. The parent/master view

Note

Notes

1. The parent/master view

The partial view needs to live inside a master/parent page, so let's create one:

@model Models.FullAndPartialViewModel
@{
ViewBag.Title = "My Master Page";
}

<script type="text/javascript" src="CDN or local jquery file"></script>

<div id="container">
<label for="ddlCategory"><strong>Select a category</strong></label>
@Html.DropDownListFor(m =>m.CategoryId,
new SelectList(Model.CategoryList, "CategoryId", "CategoryName", Model.CategoryId), new { id = "ddlCategory", @class = "test" })
<br/><br/>
<div id="dvCategoryResults">
@{Html.RenderPartial("CategoryResults", Model);}
</div>
</div>

you need a reference to the jquery. This can be either local or through a CDN <script type="text/javascript" src="CDN or local jquery file"></script>
and, you need to put your partial view inside a div as we will reference the div later in the ajax call.

2. The partial view

Note

Notes

2. The partial view

The partial view is just a very slimmed down version of a normal view. You only add the html elements that are required. The name of the view should be the same as the one used in the @Html.RenderPartial() declaration on the master view, i.e. CategoryResults

@model Models.FullAndPartialViewModel
<table>
<thead>
<tr>
<th>Category</th>
<th>Product</th>
<th>Price</th>
</tr>
</thead>
<tbody>
@foreach (var product in Model.Products)
{
<tr>
<td>@product.Category</td>
<td>@product.Product</td>
<td>@product.Product</td>
</tr>
}
</tbody>
</table>



3. The controller

Note

Notes

3. The controller

The controller consists of 3 methods:
one for loading the whole page(parent and partial) - Index()
one for reloading/refreshing the partial view - GetCategoryProducts()
and a helper method to create and populate the datamodel - GetFullAndPartialViewModel()

[HttpGet]
public async Task<ActionResult> Index()
{
var model = await this.GetFullAndPartialViewModel();
return this.View(model);
}

[HttpGet]
public async Task<ActionResult> GetCategoryProducts(string categoryId)
{
var lookupId = int.Parse(categoryId);
var model = await this.GetFullAndPartialViewModel(lookupId);
return PartialView("CategoryResults", model);
}

private async Task<FullAndPartialViewModel> GetFullAndPartialViewModel(int categoryId = 0)
{
... code omitted...
// populate the viewModel and return it
return fullAndPartialViewModel;
}




4. The DataModel

Note

Notes

4. The DataModel

public class FullAndPartialViewModel
{
public int CategoryId { get; set; }
public List<CategoryProductItem> Products { get; set; }
public List<CategoryListItem> CategoryList { get; set; }
}

5. The Ajax code

The idea here is to reload the partial view on the page when the user selects a different category from the drop down list. At the bottom of you master page, below the html, add the following javascript code:

<script type="text/javascript">
$(document).ready(function () {
$("#ddlCategory").change(function () {
var categoryId = $("#ddlCategory").val();
$("#dvCategoryResults").load('@(Url.Action("GetCategoryProducts","Home",null, Request.Url.Scheme))?categoryId=' + categoryId);
});
});
</script>



MVC Web Application with Entity Framework

Note

Notes

MVC Web Application with Entity Framework


The sample application creates a web site for Employee record and demonstrate the use of Lambda Expressions. According to Microsoft (https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/lambda-expressions) A lambda expression is an anonymous function that you can use to create delegates or expression tree types. By using lambda expressions, you can write local functions that can be passed as arguments or returned as the value of function calls. Lambda expressions are particularly helpful for writing LINQ query expressions.
In this tutorial we will focus on its use on LINQ queries.
Software versions used in the tutorial
Visual Studio 2017
.NET 4.52
Entity Framework 6 (EntityFramework 6.1.0 NuGet package)

Create Web Application
Start Visual Studio 2017,
On the Start Page -> New Project click ASP.NET Web Application


picture.jpg



Select ASP.Net Web Application .NET Framework

picture.jpg



Select MVC and click “Change Authentication”

picture.jpg


Select Individual User Account and press OK

picture.jpg



By default, Visual Studio will create a basic web site with HomeController and Views “Index”, “Contact” and “About”.

picture.jpg

Run the Application by Start Debugging from the Main Menu or press F5.


picture.jpg

You will see the standard Index Page


picture.jpg


Stop Debugging by pressing Shift F5 or from the Main Menu, Debug dropdown > Stop Debugging

picture.jpg




Create Database using Code First Migration

Note

Notes

Create Database using Code First Migration


We will add a model class “Employee” and let Entity Framework create Database Table.
Open “Solution Explorer” from the Main Menu View; right click Model folder >Add> Class


picture.jpg

In the Add New Item window enter dbModel as the Class file name

picture.jpg


Replace the content with the following contents

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;

namespace LambdaExpressions.Models
{
public class Employee
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int id { get; set; }
public string Name { get; set; }
public DateTime? Hire_Date { get; set; }
public string status {get; set;}
public string Get_PerDiem {get; set;}
public string OvertimePolicy {get; set;}
}
public class docEntities : DbContext
{
public DbSet<Employee> tblTKEmployees { get; set; }
public docEntities() : base("name=DefaultConnection")
{
}
}
}

Build Solution by pressing Ctrl+Shift+B or from the Main Menu > Build > Build Solution and in the Output window make sure you have 0 failed.

picture.jpg




Build Database using Migration tool

Note

Notes

Build Database using Migration tool


Open “Package Manager Console” from the Main Menu Tools “NuGet Package Manager”


picture.jpg


On the command prompt “PM>” of the Package Manager Console enter command “enable-migrations”
You will be prompted to select either ApplicationDbContext or DocEntities context.



picture.jpg

Select ApplicationDbContext by entering the prompt:
PM> Enable-Migrations -ContextTypeName LambdaExpressions.Models.ApplicationDbContext



picture.jpg

A Configuration file will be created. Enter command: add-migration and name it ‘app’

picture.jpg

A Migration file will be created in the Migrations directory, specifying the function to create ApplicationDbContext database tables including:
"dbo.AspNetRoles"
"dbo.AspNetUserRoles"
"dbo.AspNetUsers"
"dbo.AspNetUserClaims",
"dbo.AspNetUserLogins"



picture.jpg


Enter command
PM> update-database
Database tables will be created

picture.jpg




Notice there is only one database connection string in the Web.Config file and that is the default connection. Entering command enable-migrations DocEntities requires adding -Force option
Enter command:
PM> Enable-Migrations -ContextTypeName LambdaExpressions.Model.docEntities -Force


picture.jpg



A new migration file will be created and accept the changes to the Configuration file by pressing “Yes”

picture.jpg


Enter command ‘add-migration’ and name it ‘db’




picture.jpg


A migration file will be created for the docEntities context with a function to create Employee Table
Notice the file also has functions that are supposed to remove existing ApplicationDbContext tables. By default, the entity framework assumes two separate databases, but we would to use single database for both, the ApplicationDbContext and docEntities.


Using one database for DocEntities as well ApplicationDbContext

Note

Notes

Using one database for DocEntities as well ApplicationDbContext


You must remove the code part that was supposed to drop existing ApplicatioDbContext tables

picture.jpg

Your new configuration file should have the following contents,


picture.jpg


Enter command ‘update-database’ at the command prompt to create tables for the docEntiries context as specified in the dbModels file,
PM> update-database


Creating Views for “List”, “Edit”, “Details” and “Delete” operations on the database tables

Note

Notes

Creating Views for “List”, “Edit”, “Details” and “Delete” operations on the database tables



Visual Studio provides a very useful option “New Scaffolded Items”, it looks at the database model classes and creates Controller and Views for the List, Edit, Details and Delete operations:
Open Solution Explorer and right click Controller > Add > New Scaffolded Item.


picture.jpg


Select MVC5 Controller with Views, using Entity Framework.


picture.jpg


Select ‘Employee’ in the Model Class dropdown and select docEntities for the Data context class dropdown,


picture.jpg


A new controller EmployeeController.cs file will be created in the file Controller directory and a subdirectory Employee will be created in the Views directory with Index.cshtml, Edit.cshtml, Detail.cshtml and Create.cshtml file for the corresponding Views.
Change the HomeController Index function to Redirect to Employee Index function as shown below,


picture.jpg


Start Debugging by pressing F5,