Entity framework

997 views

Published on

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

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
997
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
35
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide
  • NhibernateOpen AccessLightSpeedEtc..
  • Give us tools and services for consuming EDM
  • Code becomes more complexLot of steps to doProblem with inheritance
  • Fast application development.No need to mapping classes to tables.
  • Definition for application modelMap between app model and database schemaMultiple inheritance hierarchy mappingsMany-to-Many without link or jump table in model
  • What this selection means is that we can either choose to generate the entity model from an existing database schema or we can design the entity model here and then later hook it up to the database. Since we already have the database ready, we will use the first option. Once the Model is generated, the Entity for each table is generated. The generated entity for our contact table is:
  • Entity framework

    1. 1. ENTITY FRAMEWORK
    2. 2. Definition: ORM • Object-Relational Mapping: • Virtual object database
    3. 3. 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
    4. 4. Definition: Linq • Language Integrated Query • Query expression in our code  Similar to SQL query • Query data from: Arrays List XML Database tables
    5. 5. Example 1 Query Data • Query: Select * from Customer • Return the data into: List<Customer>
    6. 6. Ex.1: Old school List<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();
    7. 7. 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();
    8. 8. EDM
    9. 9. Example 2 Create EDM 1- Create the database 2-Add new item
    10. 10. 3- Create the model
    11. 11. Classes for perfomingDatabaseoperationContactstable model Ex.2: Generated Classes
    12. 12. 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
    13. 13. Ex.2: Read Operation ContactsDb db = new ContactsDb(); Repeater1.DataSource = db.Contacts; Repeater1.DataBind();
    14. 14. Ex.2: Update/Delete Operations int 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();
    15. 15. 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.
    16. 16. LinQ Vs Native SQL •Disadvantages: 1. Debugging. 2. Complex queries resulting performance issues. 3. Overhead in creating queries. 4. Indexes are not well used.
    17. 17. 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 };
    18. 18. 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(); .
    19. 19. 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)
    20. 20. 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):
    21. 21. 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
    22. 22. 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; } }
    23. 23. 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"); }); } }
    24. 24. 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 
    25. 25. Q&A

    ×