25
ENTITY FRAMEWORK

Entity framework

Embed Size (px)

DESCRIPTION

The power of EF. Start using EF. What is LINQ. Performance Consideration. EF Desgin.

Citation preview

Page 1: Entity framework

ENTITY FRAMEWORK

Page 2: Entity framework

Definition: ORM• Object-Relational Mapping:• Virtual object database

Page 3: Entity framework

Definition: EF• Entity Framework•  It is an enhancement to

ADO.NET that gives developers an automated mechanism for accessing & storing the data in the database and working with the results in addition to DataReader and DataSet.

• Microsoft .Net Framework 3.5 SP1

Page 4: Entity framework

Definition: Linq• Language Integrated Query• Query expression in our code Similar to SQL query• Query data from:

ArraysListXMLDatabase tables

Page 5: Entity framework

Example 1 Query Data

• Query:

Select * from Customer

• Return the data into:

List<Customer>

Page 6: Entity framework

Ex.1: Old schoolList<Customer> Customers = new List<Customer>();

string QueryString = "Data source=localhost; initial catalog=SubwayDB; integrated security=true";SqlConnection sqlConn = new SqlConnection(QueryString);

string Query = "Select * from Customers where FirsName=@FN";SqlCommand sqlComm = new SqlCommand(Query, sqlConn);sqlComm.CommandType = System.Data.CommandType.Text;sqlComm.Parameters.AddWithValue("@FN", "test").DbType = System.Data.DbType.Int16;

sqlConn.Open();SqlDataReader reader = sqlComm.ExecuteReader();while (reader.Read()){ Customers.Add(new Customer(){ FirstName = reader["FirstName"].ToString(), LastName = reader["LastName"].ToString(), Email = reader["Email"].ToString(), });}reader.Close();sqlConn.Close();

1

2

3

Page 7: Entity framework

Ex.1: Linq• Easy:

List<Customer> Customers = from c in Customer where c.FirstName == "test"

select c;

• Quick and readable:

List<Customer>

Customers = ContextManager.CurrentContext.Customers. Where(c => c.FirstName == "test").ToList();

1

1

Page 8: Entity framework

DB ModelEntity

Model

EDM

Page 9: Entity framework

Example 2 Create EDM

1- Create the database

2- Add new item

Page 10: Entity framework

3- Create the model

Page 11: Entity framework

Classes for perfoming Database operationContacts table model

Ex.2: Generated Classes

Page 12: Entity framework

Contact con = new Contact(); con.fname = TextBox1.Text; con.lname = TextBox2.Text; con.phone = TextBox3.Text; ContactsDb db = new ContactsDb(); db.Contacts.AddObject(con); db.SaveChanges();

Ex.2: Insert Operation

Page 13: Entity framework

Ex.2: Read Operation

ContactsDb db = new ContactsDb(); Repeater1.DataSource = db.Contacts; Repeater1.DataBind();

Page 14: Entity framework

Ex.2: Update/Delete Operationsint idToupdate = Convert.ToInt32(Request.QueryString["id"].ToString()); ContactsDb db = new ContactsDb(); Contact con = db.Contacts.SingleOrDefault(p => p.id == idToupdate);

int idToupdate = Convert.ToInt32(Request.QueryString["id"].ToString()); ContactsDb db = new ContactsDb(); Contact con = db.Contacts.SingleOrDefault(p => p.id == idToupdate);

con.phone = TextBox1.Text; db.SaveChanges();

int idToupdate = Convert.ToInt32(Request.QueryString["id"].ToString()); ContactsDb db = new ContactsDb(); Contact con = db.Contacts.SingleOrDefault(p => p.id == idToupdate);

db.Contacts.DeleteObject(con); db.SaveChanges();

Page 15: Entity framework

LinQ Vs Native SQL

• Advantages:1. No magic strings, like you have in SQL queries (prevent injection).

2. Intellisense.

3. Faster development.

4. Auto-generated domain objects that are usable small projects.

5. Lazy loading.(Loading the related objects per request)

6. Lambda expressions and extension methods.

Page 16: Entity framework

LinQ Vs Native SQL

•Disadvantages:

1. Debugging.

2. Complex queries resulting performance issues.

3. Overhead in creating queries.

4. Indexes are not well used.

Page 17: Entity framework

Performance Consideration• Multiple Entity Models (multiple contexts).• Disable tracking if not needed (increase performance): SubwayDB context = new SubwayDB(); context.Configuration.AutoDetectChangesEnabled = false; // Do bulk insert ....... // Change it back context.Configuration.AutoDetectChangesEnabled = true;

• Use SQL Projection: var users = from u in context.UserAccounts where u.Active == true select new { FirstName = u.FirstName, LastName = u.LastName, Email = u.Email };

Page 18: Entity framework

Performance Consideration• Use Appropriate Collection: IQueryable<UserAccount> OR IEnumerable<UserAccount>

- filter at SQL server side - filter at client side - Support Lazy loading - No lazy loading.

• Compiled Query: - Applies to the Most frequently used queries to enhance performance.

• Use server side paging: int pageSize=10,startingPageIndex=2; var users = context.UserAccounts.Take(pageSize) .Skip(startingPageIndex * pageSize) .ToList(); .

Page 19: Entity framework

Performance Consideration• Caching: - Internal caching. - Second level caching (to be implemented)

• Fast Micro-ORM style Sql Query on Database and ExecuteStoreQuery (SP):

var query = ContextManager.CurrentContext.Database.SqlQuery<TransactionObjectList>( "EXEC sp_GetTransactionList @RoleID, @UserID, @RegionID, @Lookup, @TransactionsStatus, @DateFrom, @DateTo, " + "@AmountFrom, @AmountTo, @DeliveryMethod, @AdminMenu, @StoreNumber, @HasDiscount, @CateringMenu, " + "@DevelopmentStores, @WithCustomerAbuse, @WithTotalPrice, @minGrandTotal, @maxGrandTotal, @EnteredToSubshop, " + "@ExcludeZeroBalance, @StoreIsRemoved, @marketID, @Page,@PageSize,@sortdir,@sort", sqlparameters);

• Lazy Vs Eager loading (when to choose lazy loading)

Page 20: Entity framework

Performance Consideration• Avoid using Contains In LINQ, we use contains method for checking existence. It is converted to "WHERE IN" in

SQL which cause performance degrades.

• Debug and Optimize LINQ Query: - Using SQL profiler. - Divide the query to a multiple queries (large join tables)

• Inheritance strategies with EF:

- Table per Hierarchy (TPH)

- Table per Type (TPT)

- Table per Concrete class (TPC): 

Page 21: Entity framework

Table per Hierarchy (TPH)• Enable polymorphism by de-normalizing the SQL schema, and utilize a type

discriminator column that holds type information.

public abstract class BillingDetail

{ public int BillingDetailId { get; set; } public string Owner { get; set; } public string Number { get; set; } }

public class BankAccount : BillingDetail { public string BankName { get; set; } public string Swift { get; set; } }

public class CreditCard : BillingDetail { public int CardType { get; set; } public string ExpiryMonth { get; set; } public string ExpiryYear { get; set; } }

Discriminator = all 3 types

Page 22: Entity framework

Table per Type (TPT)• Represent "is a" (inheritance) relationships as "has a" (foreign key)

relationships..

public abstract class BillingDetail { public int BillingDetailId { get; set; } public string Owner { get; set; } public string Number { get; set; } }

[Table("BankAccounts")] public class BankAccount : BillingDetail { public string BankName { get; set; } public string Swift { get; set; } }

[Table("CreditCards")] public class CreditCard : BillingDetail { public int CardType { get; set; } public string ExpiryMonth { get; set; } public string ExpiryYear { get; set; } }

Page 23: Entity framework

Table per Concrete Type (TPC)• Discard polymorphism and inheritance relationships completely from the SQL schema.

public abstract class BillingDetail { public int BillingDetailId { get; set; } public string Owner { get; set; } public string Number { get; set; } }

public class BankAccount : BillingDetail { public string BankName { get; set; } public string Swift { get; set; } }

public class CreditCard : BillingDetail { public int CardType { get; set; } public string ExpiryMonth { get; set; } public string ExpiryYear { get; set; } }

public class InheritanceMappingContext : DbContext { public DbSet<BillingDetail> BillingDetails { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<BankAccount>().Map(m => { m.MapInheritedProperties(); m.ToTable("BankAccounts"); });

modelBuilder.Entity<CreditCard>().Map(m => { m.MapInheritedProperties(); m.ToTable("CreditCards"); }); } }

Page 24: Entity framework

Summary• Entity Framework is a Commercial Object-Relational Mapper for .NET

applications provided by Microsoft free of cost. Apart from EF, there are several mature alternatives (both Open Source and Commercial) available for .NET developers, like NHibernate and LightSpeed, along with light-weight micro-ORMs like Dapper.NET, PetaPoco and Massive.

• A good design of models and structures results in a well performing Application.

• Use Native ADO.Net with paging in case reporting large data.• Use LINQ PAD to practice

• HAPPY CODING

Page 25: Entity framework

Q&A