As No Tracking With Entity Framework Core | RAJESH GAMI

Introduction 

Entity Framework's DbContext keeps track of changes made to an entity or object and ensures that the database is updated correctly when the context method SaveChange () is called. When you use an object query to retrieve entities, Entity Framework caches them and keeps track of the changes made to them until the savechanges method is called.

Entity Framework keeps track of query results that return an entity type. You may not want to track some entities because the data is used for display purposes only and no other operations such as inserts, updates, or deletes are performed. For example, display data in a read-only grid.
In the above scenario, untracked queries are useful. Execution is very fast due to the change tracking feature. There are several ways to achieve untracked queries.
 
No-Tracking query using AsNoTracking() extention method
 
The AsNoTracking() extension method returns a new query and the returned entity is not tracked by the context. This means that EF does not perform the additional task of saving the retrieved entity for tracking.
 
Example
  1. using (EntityModelContext context = new EntityModelContext())  
  2. {  
  3.     var employee = context.Employees.AsNoTracking().ToList();    
  4.   
  5.     var employee2 = context.Employees    
  6.                     .Where(p => p.Id >= 4)    
  7.                     .AsNoTracking().ToList();    
  8. }  
Changing tracking behavior at the context instance level
 
You can also change the default tracking behavior at the Context Instance level. The ChangeTracker class (defined as a property of the context class) has a property QueryTrackingBehavior that you can use to change the tracking behavior.
 
Example
  1. using (EntityModelContext context = new EntityModelContext())  
  2. {  
  3.     context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;  
  4.     ...  
  5.     ...  
  6. }  
If the result set does not contain the entity type, no tracking will be performed.
 
If the query result does not contain the entity type, it will not be tracked by the change tracker and no tracking will be performed. No tracking is performed in the following query. This query returns an anonymous type that contains some of the entity values.
  1. var data2 = context.Employees.Select(p => new  
  2.                 {  
  3.                     name = p.Name,  
  4.                     id = p.Id  
  5.   
  6.                 }).ToList();  
Because the result contains the entity type, the result set may not return the entity even if that entity is tracked by default. In the following query, the result is an anonymous type, but it is tracked because the employee instance is included in the result set.
  1. var data2 = context.Employees.Select(emp => new  
  2.                {  
  3.                    Id = emp.Id,  
  4.                 Employee = emp  
  5.   
  6.                }).ToList();  
No Tracking saves both execution time and memory usage. Applying this option is very important when retrieving large amounts of data from the database for read-only purposes.
 

    How to write in Hindi font (or other language font) in HTML | ASP.NET Core | Rajesh Gami

    How to write in Hindi font (or other language font) in HTML | ASP.NET Core

     
    This blog will show you how to read and write in Hindi (or you can use any language you want).
    This section describes how to use the Devlys_010 font to write Hindi in ASP.NET Core text fields. Therefore, follow the steps below.

    Step 1 
    Download Devlys_010 font in any format such as .ttf, .woff, etc. You can download from here 
    This is a ZIP file, so you can unzip it into a folder.

    Step 2 
    Open the Asp.Net Core project and create a new folder under CSS. Give the folder a name like Fonts.
    Paste the downloaded fonts into the Fonts folder. Then create a CSS file and name it font.css.
     
    How to write in Hindi (Or another font) in Asp.Net Core 
     

    You can see that we have added a screenshot here. I inserted the fonts in ttf format and created font.css in the newly created "Fonts" folder.

    Step 3 
    Now open font.css in the editor. Next, let's add fonts to the project using @ font-face. Therefore, write the CSS code in font.css as follows:
    1. @font-face {  
    2.     font-family'Devlys_010';  
    3.     srclocal('Devlys_010'),url('./Devlys_010.ttf'format('truetype');  
    4. }  
    Step 4
    Next, create a new CSS class under @ font-face in font.css and add the font family used by @font-face.
    1. .hFont {  
    2.     font-family'Devlys_010' !important;  
    3. }  
    Now you can see all the CSS code in font.css.
    1. @font-face {  
    2.     font-family'Devlys_010';  
    3.     srclocal('Devlys_010'),url('./Devlys_010.ttf'format('truetype');  
    4. }  
    5.   
    6. .hFont {  
    7.     font-family'Devlys_010' !important;  
    8. }  
    Now I added the .hFont class. You can change this name.

    Step 5
     
    Next, go to the cshtml page where you want to write the Hindi font. So if you use the text input type, just add the hFont class as follows:
    Then add CSS to the header to get the CSS code.
    1. <link href="~/css/fonts/font.css" rel="stylesheet" />  
    Now add a CSS class to create a Hindi font. See the code below. Added hFont class to input type.
    1. <input asp-for="@Model.AdminMaster.AdminName" class="form-control hFont" id="txtAdminName" />  

    2. OR

    3. <input type = "text" class="form-control hFont" id="txtAdminName" />  
    Note
    You can use other fonts just by adding and using fonts in CSS. Also, use language fonts such as Gujarati, Marathi, Urdu, or other languages.

    Reference from my C# Corner blog : C# Corner Blog Link

    How to use View Model in MVC | Rajesh Gami

    Summary

    The view model in asp.net mvc represents only the data to display, regardless of whether it is used for display or to get input from the view. If you want to display multiple models in asp.net mvc, you need to create a new view model. The following image shows a visual representation of the view model in asp.net mvc.

    Here we will learn asp.net mvc viewmodel using a simple example with a Customer entity and an Order entity. To display the data of both entities (Customer Entity + Order Entity), you need to create a view model (CustomerVM), select the properties to display from both Entity (Customer Entity + Order Entity) and model It is displayed.

    viewmodel structure in asp.net mvc application
    Then start creating the view model in asp.netmvc before looking at the tables used by your application.

    Database part

    In this database part, use the following script to create the required tables in the database.

    Customer table

    Below is a script to create a customer table in the database.

    CREATE TABLE [dbo].[Customer](
    [CustomerID] [int] IDENTITY(1,1) NOT NULL Primary key,
    [Name] [varchar](100) NULL,
    [Address] [varchar](300) NULL,
    [Mobileno] [varchar](15) NULL,
    [Birthdate] [datetime] NULL,
    [EmailID] [varchar](300) NULL,)
    Running the above script will create a customer table as shown below.

    Customer Table in Database in sql server

    Order table

    Below is a script to create an order table in the database.

    CREATE TABLE [dbo].[Order](
    [OrderID] [int] IDENTITY(1,1) NOT NULL primary key,
    [CustomerID] [int] NULL,
    [OrderDate] [datetime] NULL,
    [OrderPrice] [decimal](18, 0) NULL,)

    Creating an Asp.Net MVC Application  

    Creating an Asp.Net MVC application VisualStudio Select Go To File> New > Select >Project

    create new asp.net mvc project from visual studio 2012

    After that, a new dialog box will appear where you can select the template and project type. Under Templates, under Web, select Visual C ++, and under Project Type, select ASP.NET MVC 4 Web Application. Name it "TutorialViewModel" here, and click the [OK] button at the end.

    give name of project as viewmodel in asp.net mvc application

    After giving a name, click [OK] to display a new dialog. To select a template in this, select the base template and click OK as shown below.

    select basic template to create new application in asp.net mvc

    After building the application, this is the complete folder view.

    viewmodel structure in asp.net mvc application

    Installing Entity Framework on your application

    To add Entity Framework, right-click on the application and select Manage NuGet Packages from the list.

    install entity framework in asp.net mvc application

    Once selected, a new dialog box called Manage NuGet Packages will appear in the search box, where you can type Entity Framework. After getting the search value, select Entity Framework and click the Install button.

    Installing Entity Framework in Asp.net mvc application

        After adding a green OK symbol will be displayed.
    After install entity framework in asp.net mvc application

    After adding Entity Framework, add the ADO.NET Entity Data Model.

    Adding ADO.NET Entity Data Model

    To add an ADO.NET entity data model, right-click on the model folder and select Add Inside. Select the ADO.NET entity data model as shown below.

    Add ado.net entity data model in asp.net mvc application

    Enter any name, but it must be unique and click the OK button.

    customerorderdb entity name in asp.net mvc application
    Then you will see a new wizard that configures the entity data model. In this case, use database first.

    Choose Model Content for Ado.net model in database first approach

    Then select Generate from database and click Next. Click the Next button to display the new data connection selection wizard. Select a data connection

     Data base connection

    Choose new database connection in viewmodel example

    Then click New Connection to bring up a new dialog. You need to configure it here. Under Server Name, you need to add the SQL Server name and select Use Windows Authentication or Use SQL Server Authentication to connect to SQL Server. Here, I selected Use SQL Server Authentication and entered the SQL server user name and password. Finally, select the database name "OrderDB". When you're done, click the OK button as shown below.

    Create new database connection in model first approach in asp.net mvc

    After adding the database connection, the Entity Data Model Wizard looks like this:

    selecting entity data model new database connection in asp.net mvc

    A new wizard for selecting database objects is displayed, showing all the tables you have created in the database.
    select order table from database in asp.net mvc
    Finally, click the Finish button. This is a snapshot after adding the ADO.NET entity data model.

    Project structure after adding ado.net entity model in asp.net mvc applicaiton

    ViewModels Folder

    Next, let's add the ViewModels folder to the project and keep all the ViewModels in the same folder.

    add viewmodel folder in asp.net mvc application

    Adding CustomerVM to the ViewModels folder

    Add a ViewModel named CustomerVM.cs to this folder. Click the ViewModels folder, select Add, and finally select Class as shown in

    add new class in viewmodel folder in asp.net mvc
    When you select a class, the Add New Item dialog box is displayed for this selected class, give name CustomerVM.cs.

    give name to class file in asp.net mvc application

    After adding the CustomerVM view model with the code shown below

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;

    namespace TutorialViewModel.ViewModels
    {
    public class CustomerVM
    {

    }
    }
    Let's see the domain model entity we added

    Customer Entity

    namespace TutorialViewModel.Models
    {
    using System;
    using System.Collections.Generic;

    public partial class Customer
    {
    public int CustomerID { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string Mobileno { get; set; }
    public Nullable<System.DateTime> Birthdate { get; set; }
    public string EmailID { get; set; }
    }
    }

    Order Entity

    namespace TutorialViewModel.Models
    {
    using System;
    using System.Collections.Generic;

    public partial class Order
    {
    public int OrderID { get; set; }
    public Nullable<int> CustomerID { get; set; }
    public Nullable<System.DateTime> OrderDate { get; set; }
    public Nullable<decimal> OrderPrice { get; set; }
    }
    }

    ViewModel (CustomerVM.cs)

    After checking the entity, let's add the properties of both models to the CustomerVM class. I got the name, address, mobile number from the customer model, got the order date and price from the order model, and displayed them in the View.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;

    namespace TutorialViewModel.ViewModels
    {
    public class CustomerVM
    {
    public string Name { get; set; } // Customer
    public string Address { get; set; } // Customer
    public string Mobileno { get; set; } // Customer
    public Nullable<System.DateTime> OrderDate { get; set; } // Order
    public Nullable<decimal> OrderPrice { get; set; } // Order
    }
    }
    After creating ViewModel (CustomerVM) added controller with Name CustomerOrderDetails.

    Add a Controller in Application

    To add a controller, right-click the Controllers folder and select Add> Controller.

    add new controller in asp.net mvc application

    When you select a controller, a new dialog "Add Controller" is displayed. In this dialog, add the name "CustomerOrderDetailsController", select "Empty MVC Controller" in the template, and click the "Add" button.

    give name to controller in viewmodel asp.net mvc application

    After adding the controller "CustomerOrderDetailsController" containing the code as shown below

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;

    namespace TutorialViewModel.Controllers
    {
    public class CustomerOrderDetailsController : Controller
    {

    [AcceptVerbs(HttpVerbs.Get)]
    public ActionResult Index()
    {
    return View();
    }

    }
    }

    Controller Action Methods (Index)

    Then write the code in this controller to get the value from the database and populate the ViewModel (CustomerVM) with the data

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using TutorialViewModel.Models;
    using TutorialViewModel.ViewModels;
    namespace TutorialViewModel.Controllers
    {
    public class CustomerOrderDetailsController : Controller
    {
    [AcceptVerbs(HttpVerbs.Get)]
    public ActionResult Index()
    {
    OrderDBEntities orderdb = new OrderDBEntities(); //dbcontect class
    List<CustomerVM> CustomerVMlist = new List<CustomerVM>(); // to hold list of Customer and order details
    var customerlist = (from Cust in orderdb.Customers
    join Ord in orderdb.Orders on Cust.CustomerID equals Ord.CustomerID
    selectnew { Cust.Name, Cust.Mobileno, Cust.Address, Ord.OrderDate, Ord.OrderPrice}).ToList();
    //query getting data from database from joining two tables and storing data in customerlist
    foreach (var item in customerlist)
    {
    CustomerVM objcvm = new CustomerVM(); // ViewModel
    objcvm.Name = item.Name;
    objcvm.Mobileno = item.Mobileno;
    objcvm.Address = item.Address;
    objcvm.OrderDate = item.OrderDate;
    objcvm.OrderPrice = item.OrderPrice;
    CustomerVMlist.Add(objcvm);
    }
    //Using foreach loop fill data from custmerlist to List<CustomerVM>.
    return View(CustomerVMlist); //List of CustomerVM (ViewModel)
    }
    }
    }

    This controller gets the data from the database, joins both tables with (CustomerID), saves it in (CustomerList), applies a foreach loop to get this data in (List CustomerVMlist), and finally I have created a linq query to send and display to view

    Add View to your application

    To add a view, right-click the Index ActionResult method and select Add View to create a view template for the index form. In the snapshot below, we will create a strongly typed View with the View engine selected as the Razor and the CustomerVM model class selected, and a List form with the List selected in the Scaffold template. Finally, click the Add button.

    Give name to view in viewmodel in asp.net mvc application

    Folder structure

    after add view our viewmodel asp.net mvc project structure

    Index.cshtml View 

    Adding the view will generate the complete code for Index.cshtml below.

    @model IEnumerable<TutorialViewModel.ViewModels.CustomerVM>
    @{
        Layout = null;
    }
    <!DOCTYPE html>
    <html>
    <head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
    </head>
    <body>
    <table cellspacing="5px;">
    <tr>
    <th>
    @Html.DisplayNameFor(model => model.Name)
    </th>
    <th>
    @Html.DisplayNameFor(model => model.Address)
    </th>
    <th>
    @Html.DisplayNameFor(model => model.Mobileno)
    </th>
    <th>
    @Html.DisplayNameFor(model => model.OrderDate)
    </th>
    <th>
    @Html.DisplayNameFor(model => model.OrderPrice)
    </th>
    </tr>
    @foreach (var item in Model) {
    <tr>
    <td>
    @Html.DisplayFor(modelItem => item.Name)
    </td>
    <td>
    @Html.DisplayFor(modelItem => item.Address)
    </td>
    <td>
    @Html.DisplayFor(modelItem => item.Mobileno)
    </td>
    <td>
    @Html.DisplayFor(modelItem => item.OrderDate)
    </td>
    <td>
    @Html.DisplayFor(modelItem => item.OrderPrice)
    </td>
    </tr>
    }
    </table>
    </body>
    </html>

    In the view generated above, we have data from both the Customer model and the Order model, we saved the data in the CustomerVM (ViewModel) and displayed it at the end. Both the customer table and the order table contain the data shown below

    tables data in asp.net mvc applicaiton

    Then run the application and enter a URL like http: // localhost: ##### / CustomerOrderDetails / index to access the page.

    Output:

    output of viewmodel data in asp.net mvc application

    .net mvc is easy to use and always uses ViewModels to clarify in information how to display the data and how to get the input data from different domain models.
    Therefore, you can create a view model in asp.net mvc and use it in your mvc application if you want.

    RAJESH GAMI - Blog

    Digital Signature Pad in Angular | RAJESH GAMI

      What is Signature Pad? Signature Pad could be a JavaScript library for drawing fancy signatures. It supports HTML5 canvas and uses variabl...