Chapter 7 Linq and Framwork
Chapter 7 Linq and Framwork
• The .NET framework can work with several programming languages such as C#,
VB.NET, C++ and F#. At Grand Circus, we use C#.
2022
4- EF Design: EFBasics
(
https://www.entityframeworktutorial.net/what-is-entityfra
mework.aspx
)
• You compose queries using UML model (Domain classes, Entity Data Model-EDM)
• You add instances to object collection
• You delete from object collection
• You modify properties of an object
• And then you write back these changes to databases
• Slide 40 illustrates where the Entity Framework fits into your application.
4- EF Design: EFBasics
1. What is Entity Framework?
• Prior to .NET 3.5, developers often used to write ADO.NET code or Enterprise Data Access Block to save or retrieve
application data from the underlying database
• They used to open a connection to the database, create basic.net query objects to fetch data, create DataSets to
store fetched data, modify and validate data with datasets, submit data to the databases.
• What are business rules:
• Are annotation rules applied on DTO object properties, or for advanced rules, are applied via partial class (service class)
• Example of business rules
• Employee age must be greater or equal to 18
• Employees must have learners license for at least three months which should not be expired (means should not be older than 12
months)
• Employee Address attribute must not be empty
• Employees Matched regex phone number: "425-555-BOGUS"
• With EF, business rules are applied on DTOs
• Where they must be configured and why
• Validation and business rules are preferred to be implemented at the DTO model instead of JavaScript at the Front End
• The rules related to a DTO are auto generated with HTML redirected to front-end as AJAX and JavaScripts
• This View POSTS to a controller action methods having the DTO model as input parameter
• Partial classes can be added to DTO for advanced Business Rule that are validated at the controller level
• Why they must be defined at the DTO model?
• Having the flexibility to change business rules in one place, without having these changes ripple throughout the application, is a sign
of a well-written application
• Security: The complex rules are defined at Back end not Front End
• Note Annex1 for more information about implementing Business Rules with partial classes
Entity Framework
4- EF Design: EFBasics : MVC: Architecture API
Layers: presentation layer, Application layer: DTO (model Layer)+ BL services layer + EDM Entities are used by the repositories code
Repositories, EF Entities layer, database layer
Entity Data Layer
Application
Business Layer
logic
Service Layer+Repositories
Presentation layer
1-[Service Layer
(BusinessLogic)]
2-Repositories+Interfaces The
Database
+Service Layer can be :
MSSQL,
DTOs are decorated by ORACLE,
Annnotation.Val(BL) and by MySql,
Partial classes: BL Service layer Repositories use PostgreSQL,
Used to Validate DTO into:
1-Controllers context class to MonGOdb,
2-Browsers by using JS Scripts manipulate the EDM …
defined into Views
Service layer: it operates on DTO to enforce Data Transfer Object (DTO) or ViewModel + [Service layer(Business Logic)]
business rule, calculation, transformation, etc. Library to be used at any layer
4- EF Design: EFBasics
1. What is Entity Framework?
• Entity Data Model
Standard
4- EF Design: EFBasics
1. What is Entity Framework?
• Entity Data Model object collection
• In repositories, instance of context class is created and used
Inheritance
4- EF Design: EFBasics
1. What is Entity Framework?
• As per the MVC architecture figure, Entity Framework API fits between the
EDM (domain classes) and the database.
In repositories
4- EF Design: EFBasics
first to override default and annotation configurations
of the model class and to change the default mapping t
o the database
Default conventions:
2. What is an Entity in Entity Framework?: TableName= EntityName,
• Context Class: Mapping between entities and database table Attributes=Entity Property,
ForeignKey=NavPropertyName+Id,
Protected override void OnModelingCreating (ModelBuilder modelBuilder){ Ondelete is cascade by default,
VS 2019 Syntax
Child Entity
Parent Entity
EDM
Child-Parent
This code is useful with Code
4- EF Design: EFBasics
first to override default and annotation configurations
of the model class and to change the default mapping t
o the database
Syntax2
Child-Parent
.ToTable, .Property, .HasOne,… are Fluent APIs
4- EF Design: EFBasics
2. What is an Entity in Entity Framework?:
LINQ query example 1 recall
Category 1 …. * Student
Context class:
Navigation from Student to Standard using the Standard reference navigation property
4- EF Design: EFBasics
2. What is an Entity in Entity Framework?:
LINQ query example 2
Category 1 …. * Student
Context class:
• Code First
4- EF Design: EF Core
4. Development Approaches with Entity Framework: DB First
• The DbContext class and all the mappings are created first by the EF API
• The DbContext class has a method called OnModelCreating that takes an instance of
ModelBuilder class as a parameter.
• This method contains a code describing the mapping between the EDM and the database, and, with
DBFirst, is useful only as documentation
• Each time the database is modified, the context collections, the EDM, and the mapping into
OnModelCreating method of the context class have to be regenerated by rerunning the scaffold
Scaffold-DbContext
"Server=YourServerName;Database=SchoolDB;Trusted_Connection=True;MultipleActiveResultSets=t
rue; trustServerCertificate=true;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models –
Force
• Remark:
• With code first, the code in OnModelCreating is optional and is used by EF API, to override default and
annotation configurations of the model class, thus changing the default mapping to the database, add
unique Foreign constraint, custom query logic, such as advanced filtering, sorting, or joining operation
• If you want to manage database schema changes based on code into OnModelCreating, you should
consider using the Code-First approach
4- EF Design: EF Core
4. Development Approaches with Entity Framework: DB First
PRACTICE3 : DB First
a. Startup SQLServer 2014 and attach the schooldb database
b. Startup your vs2022 and create an MVC .net Core Web App
c. Go to Tools -> NuGet Package Manager -> Package Manager Console and:
1. Open the properties of the project and Adjust/check the .net core framework to version 6
2. Install-Package Microsoft.EntityFrameworkCore.SqlServer -version 7.0.2
3. install-package Microsoft.EntityframeworkCore.Tools -version 7.0.2
4. install-package Microsoft.EntityframeworkCore -version 7.0.2
5. install-package Microsoft.VisualStudio.Web.CodeGeneration.Design -version 6.0.12
6. install-package Newtonsoft.Json -version 13.0.2
7. Create your conceptual model:
Scaffold-DbContext
"Server=YourServerName;Database=SchoolDB;Trusted_Connection=True;MultipleActiveResultSets=true;
trustServerCertificate=true" tMicrosoft.EntityFrameworkCore.SqlServer -OutputDir DBEFModels –Force
Check the context class and the OnModelCreating method into the context class
Note that, in DBFirst, in general the purpose of this method is to list the mapping between the
entities and the MSSQL tables
4- EF Design: EF Core
4. Development Approaches with Entity Framework: DB First
PRACTICE3 : DB First
After scaffolding you should obtain the following
In the application add the following folders that contain the StudentDTO and the StandardDTO Described in the next slides
APL
4- EF Design: EF Core
Practice3 Continued
6. When again migrating Domain classes to database, EF Core API will adjust the tables with the modifications
4- EF Design: EF Core
4. Development Approaches with Entity Framework: Code First
• Code First Approach: Category 1 …. * Student Category Student
4-10 is not
5 null Allowed.
Std 10 has
Now 2 adr 1 and 4
3-40 is not
Allowed.(PK)
1 0..1 10 ad1
10 ad2
In Two: Not allowed
Address unique key:10 ad1,20 ad1 is not allowed
StudentAddressId StudentId
1 10
1 =>unique
2 10
2
4- EF Design: EF Core
4. Development Approaches with Entity Framework: Code First
Remark: Student 1 …. 0..1 StudentAddress (Parent ---- Child) : Use the convention of one Key
Unique Key
Not null
Address
{ optionsBuilder.UseSqlServer(@"Server=Home;Database=Practice4MethodFirstSchoolDB;Trusted_Conne
ction=True; trustServerCertificate=true");
}
}
4- EF Design: EF Core
https://www.entityframeworktutorial.net/efcore/entity-framework-core.aspx
4. Development Approaches with Entity Framework: Code First
Practice4: Code First. Use the same project created in practice3
• Given the classes:
• Student2(int StudentId, string Name) 0..1 ----- * Course2(int CourseId, string CourseName)
• Create within your application the folder named CodeFirstModel as depicted:
• Create the classes Student2 and Course2, their
navigations (Ref S62-63) and the context class
School2Context
• Add a migration for your Model
• Update your Database
• Open and Check the class created under the migration
folder:
• What is the purpose of this class ?
• Confirm that the database school2 is created in MSSQL
and verify the relationships by rightCliking Course2,
Design, rightckick anywhere into your empty screen,
Click Relationships, check the PK, FK and allow null
For StudentId
4- EF Design: EF Core
B-
Student2 0..1 <------ 0..1 StudentAddress2(int StudentAddressId , Address, City)
Consider StudentAddress is the child
C-
Addition practice: adjust the code for practice 3 for:
Student2(int StudentId, string Name) * ----- * Course2(int CourseId, string CourseName)
https://www.entityframeworktutorial.net/efcore/configure-many-to-many-relationship-in-ef-cor
e.aspx
4- EF Design: EF Core
Student2(int StudentId, string Name) * ----- * Course2(int CourseId, string CourseName) Continued : Database
In the application add the following folders that contain the StudentDTO and the StandardDTO Described in the next slides
APL
4- EF Design: EF Core - More on Transaction
• By default, if the database provider supports transactions, all
changes in a single call to SaveChanges are applied in a transaction.
• If any of the changes fail, then the transaction is rolled back and
none of the changes are applied to the database.
• Extension Methods:
• https://www.geeksforgeeks.org/extension-method-in-c-sharp/
• Any data structure that implements IQueryable or IEnumerable,
can benefit from the static extension class methods defined into
the LINQ API (S81, 82)
• Query Syntax starts with from clause and must end with
Select or GroupBy clause.
5- More on LINQ query
• https://www.tutorialsteacher.com/linq/linq-tutorials
TextBox: Bill’ --
5- More on LINQ query
• This case could not occur with LINQ:
EF6DBFIRST
EF6DBFIRST
6- IOC & Dependency Injection
1. Coupling Classes
2. Inversion Of Control
3. Dependency Injection
6- IOC & Dependency Injection
1- Coupling Classes
• By applying the Dependency Inversion Principles (DIP) you will end by loosely coupled class
• Highly coupled classes
• When one class, c1 (dependent), depends on another, c2 (dependency) that means c1 uses an instance of
c2 and that c1 could not be used unless c2’s design is completed.
• There exists more then one class like c1 that depends on c2
• Changes in c2 name will lead to errors when using dependent classes
• Loosely coupled means changes in the loosely coupled class should not force other classes to change, so
the dependent classes can become maintainable, extendable and testable
• Maintainable: you can change the name of the loosely coupled (dependency) class implementing different
method coding without worrying about other classes depending on it
• Testable : classes depending on loosely coupled classes can be tested as a unit because a mock class
with name1 can be used instead of a concrete one with name2 without any modification in the dependent
class
• Extendable : if your class is loosely coupled, then any other class that extends it can be easily loosely
6- IOC & Dependency Injection
1-Coupling Classes/Inversion Of Control (IOC)
• To explain this:
• Suppose you drive a car to your work place. This means you control the car. The IoC
principle suggests to invert the control, meaning that instead of driving the car yourself,
you hire a person that will drive the car.
6- IOC & Dependency Injection
1-Coupling Classes/DI principle
• The DI Principle definition (DIP)
• The injector class creates an instance of the service class, and injects that object into a client class so
the class does not need to instantiate the service class
• => The injector perform the job of instantiation instead of the Client class, thus the Injector implements the IoC
• The injection of the service class into the client class can be via the client Constructor or via a client
Property injection
6- IOC & Dependency Injection
3- Dependency Injection
Service1
Service2
=> Service3
IService
=> (First DIP)
• In this case an instance of the CustDataAccess class needs to be injected into the
CustomerBusinessLogic class by using an IoC injector class as prescribed before.
• For different implementation, we need to change the service name three times and use three injectors
each one is for each class
• If the Services have the same signature (methods and params) => IService
6- IOC & Dependency Injection
3- Dependency Injection
• Dependency Injection (DI) is a design pattern used to implement IoC
• Conclusion
• One way to auto inject different versions of a dependency service class is by using the
IoC Container framework
public class EmployeeDetails These classes do not follow the “ IoC and the
{ Dependency Inversion Principle” as the higher-
public int HoursWorked { get; set; } level class EmployeeDetails is directly depending
public int HourlyRate { get; set; } upon the lower level SalaryCalculator class
public float GetSalary()
{
var salaryCalculator = new SalaryCalculator();
return salaryCalculator.CalculateSalary(HoursWorked, HourlyRate);
}
}
6- IOC & Dependency Injection
3- Dependency Injection
Same code with Dependency Injection
• All the DI IoC containers must provide easy support for the following DI lifecycle:
• Register: The container must know which dependency to instantiate when it encounters a
particular type or Interface.
• Resolve:
• The di Resolver will automatically creates instances of the injected service classes when needed by the
hosting classes and inject them into the hosting class constructor
• Dispose: The container must manage the lifetime of the dependency objects.
6- IOC & Dependency Injection
3- IoC container (A.K.A DI containers)
• Application
• Register: Services required to startup the application are registered into the
IoC DI container that makes configured services available throughout an app.
• In MVC CORE, a service class can be DBContext class, customer service class like,
Repository class, MailService, etc, or .net framework classes (RazorPages,
ControllerWithView,..)
options.UseSqlServer( builder.Configuration.GetConnectionString(
"SchoolDBConnectionString")));
Into the ShoolDBController::
Delegates in C#
7- Delegates
• C# delegates are similar to pointers to functions and presents
references to methods with a particular parameter list and return
type
nc = nc1;
nc += nc2;
//calling multicast
public static int MultNum(int q) {
int r=nc(5); 15, 15*5
num *= q;
Console.WriteLine("Value of Num: {0}", r);
return num;
Console.ReadKey();
}
Value of Num: 75
7- Delegates
Passing delegates as params
// this method takes the delegate as parameter and uses it to
// call the methods as required
static FileStream fs; public static void sendString(printString ps) {
static StreamWriter sw; ps("Hello World");
}
// delegate declaration
public delegate void printString(string s);
• That means unless the web method is not finished, our form /View/Calling method processing is
blocked
• For example for a book title you call many Web API methods that return the cost of the title by
individual suppliers
• If you call the web methods in synchronous fashion, the total time taken will be the summation of the
processing time taken by the individual web methods
• On the other hand, if you call the web methods in asynchronous fashion, the time taken will be reduced
to the processing time taken by the lengthiest web method
8- Asynchronous Programming
• Asynchronous Call.
8- Asynchronous Programming
• Asynchronous programming is a means of parallel programming in which a unit of
work runs separately from the main application thread and notifies the calling thread of
its completion, failure or progress
• The main benefits of asynchronous programming using async / await include the
following: Increase the performance (Thread pool) and responsiveness (Parallel
execution) of your application, particularly when you have long-running operations
that do not require to block the execution
8- Asynchronous Programming
• 3 patterns for asynchronous programming
Console.WriteLine("hi before");
Task<int> d = Hi_async(); //Note the return type of an async method
for (int i = 0; i <= 1000; i++)
label1.Text = "Hi " + i.ToString().Trim();
2. A request starts in the same way by fetching a thread from the thread pool.
4. It instructs the .NET runtime that we expect the method call to take a while to complete.
5. When await, the calling program blocks, the calling thread will be freed ASAP, returned to the calling program to continue
the work if exists, then put back in the thread pool.
6. Another thread from the pool continue the await execution to the END. Selecting thread from the pool is very fast because
it is in a waiting state not blocked one, thus does not involve a context switching creation
8. After await done, we are not guaranteed to get the same thread back: When the asynchronous operation is completed, a
callback is scheduled to execute the code that follows the await keyword (the continuation). This callback may run on a
thread from a thread pool, not necessarily the original calling thread used in step 6
Use delegate for interThread
Communication
• private delegate void delegateName (Type data);
public static async Task SendPdfWithMails ()
{
• Code: delegateName dl = new delegateName(mailStatus);
int count = 0;
public static async void callMethod() { await Task.Run(() =>
{
Task<int> d = SendPdfWithMails(); for (int i = 0; i < 100; i++)
………… {
//Proccess to send mail, print pdf,…
} count += 1;
// delegate to add to a collection the status of each sent
//mail
private static void mailSatus(Type data) { dl(DATA);
//Task.Delay(200).Wait();
if (data !=null) {… }; }
});
} }
Remark:
it is a good practice to always write Async Simulate Async sending mails
method, so we can profit when needed from
the Async advantages
8- Asynchronous Programming
Remark: sometimes we need to block an Asyn call:
public static async void callMethod() {
int count =await SendPdfWithMails(); //Option 1 the method is blocked here, continue same TH
//or // until a running code in encountered with await
//Task<int> task=SendPdfWithMails(); //Option 2
//int count = await task; //the method is blocked here, continue same TH
Console.WriteLine("count=" + count); // until a running code in encountered with await
=====================
public static async Task<int> SendPdfWithMails ()
{
int count = 0;
await Task.Run(() => // Pick up other thread than the calling method
{
for (int i = 0; i < 100; i++)
{
//Proccess to send mail
count += 1;
Task.Delay(200).Wait(); //simulate a long work to make sure that we can suspend this code
}
});
return count;
}