Entity Framework §Petr Svirák §2015 Migrations •Provides better control over individual versions of code-first database models •Can be controlled both in Package Manager Console (poweshell console) and code •Initial migration •Created after Enable-Migrations –ContextTypeName is called •How use migrations during development •MigrateDatabaseToLatestVersion database initializer •No real data*/before first deployment: •AutomaticMigrationsEnabled = true; •AutomaticMigrationDataLossAllowed = true; •Seeding in DbMigrationsConfiguration.Seed method •With real data/after deployment: •AutomaticMigrationsEnabled = false; •No seeding •Call Add-Migration and Update-Database manually after each models change iteration • • §Entity Framework Move DataProviders into stand-alone class library •Reference EF and Microsoft.Asp.Identity nugets •Mention no app.config needed and web.config is used (from executable) •Alernate migration Configuration – especially MigrationsDirectory = @"GamesDbMigrations\Migrations"; •Create public DatabaseConfig.cs with DbInitializer set to MigrateDatabaseToLatestVersion Show Model change (when no migrations stored) •Create new entity Developer •Run application and show DB change in SQL studio •Show that FirstName, LastName and Name does not make sense – make Name virtual, override it with „full name“ meaning and add NotMapped attribute •Run application again and show DB changes in SQL studio Disable AutoMigrations and add relation of developer to the studio •Show initializer will fail •Create named migration •Explain Up and Down •Show initializer will NOT fail More about migrations •Named migrations can be manually updated •Running Update-Database –TargetMigration –Script –Force will •Create SQL script to migrate DB to given migration •Re-run migration and re-seed database •In production, always use NullDatabaseInitializer to prevent data-loss. •If not initializer set, CreateDatabaseIfNotExists is used •When not using migrations, DropCreateDatabaseAlways and DropCreateDatabaseIfModelChanges are frequently used • • § §https://app.pluralsight.com/library/courses/efmigrations/ § §Entity Framework •Add [DatabaseGenerated(DatabaseGeneratedOption.Identity)] to the Entity •Remove Id = Guid.New(); from seeds •Show that EF will create extra new migration instead of edition as it was applied; revert back according to sugestion •Show different Up and Down •Manually add to the new contraints: , defaultValueSql: "NEWID()" – no seed otherwise (bug in EF) •Show update-database and update-database –Script (-Force) •it is necessary to revert to previous migration or –Force parameter to re-apply •Run application again and show DB changes in SQL studio Context set-up •DbContext base class has string-parametered constructor with connection string itself or its name (preferably use „name=“ in the second case *) • •Database property provides access to various aspects of database and its connection. •Database.Log – allows custom logging of queries and commands executed in the context •Database.CommandTimeout – amout of time to wait before an command is interupted •Database.Connection.StateChange – event executed on any change to the state of connection (opened, closed, ...) •Configuration property provides access to various aspects of entity framework behaviour in the context – Each property is important and well described • •Both properties are available publicly in each instance. Always consider whether modify all instances of the context (by using constructor) or individual instances (by amending a property, for example, in a context instance in a given controller) § §* http://stackoverflow.com/a/25057557/1138663 • §Entity Framework Context ctor •In Database: Show logging, set a command time-out, add StateChange event •In Configuration: Show AutoDetectChangesEnabled and LazyLoadingEnabled and ProxyCreationEnabled Context models creation •Either via DataAnnotations attributes •Or via overriding OnModelCreating method in a context itself •Entity Framework Fluent API •Wider variety of posibilities available (than attributes provide) •modelBuilder.Configurations – data anotations stored in separated implementations of EntityTypeConfiguration base class. •modelBuilder.Conventions – rules based on properties for (all) models in the context, stored in separate implementations of IConvention (or Convention base class more preciously) •modelBuilder.Properties – context-wide lightweight conventions •modelBuilder.Entity – relations definition, entity-specific lightweight configurations and conventions • §Entity Framework Override OnModelCreating method in cotext •Add different max length for Games and Studios names •Add a table a custom name for one of entities •Show there is MapToStoredProcedures to use Insert, Update, Delete SP instead of commands •Create a convention for all Guid properties with name ID, so they are (primary) keys and auto-generated •Move all the configurations and conventions to internal classes (extending EntityTypeConfiguration<> and Convention respectively) •Add a migration and show it still all works but SQL changed Lazy loading (and proxies) •If enabled (default), virtual properties representing (other) entities or collections of entities are not queried with the main object itself, but later upon first request/access to given property in code. •This is done by using automaticaly (run-time) generated proxy types overriding the very virtual properties and replacing their getter with a loading hook. § § § § § § §https://msdn.microsoft.com/en-us/data/jj574232.aspx#lazy § §Entity Framework Continue to Earger slide Eager loading •For queries where it is known that certain properties/related entities will be accessed, eager loading is more suitable as there is only one query to the database, rather than a new query for each virtual property of each object that was accessed for the first time. •..Include(entity => entity.Property) – notifies Entity Framework to query entity/entities stored in the Property along with entity stored in . • • • • • § §https://msdn.microsoft.com/en-us/data/jj574232.aspx#eager § §Entity Framework Create StudiosController using scaffolding Create IndexViewModel and StudioViewModel and DeveloperViewModel Append logging from DbContext into the IndexViewModel, measure StartTime in theIndexViewModel Add a view, show all properties of the model and time and queries it takes on 2 sample Studios Unit of Work •Design pattern •Each DbContext acts as a unit of work. •Changes made to entities are tracked and persit in memory •Each SaveChanges() call succeeds fully or nowise (change are persisted only all-together) •Bigger the context is, more memory it possible drains and more responsibilies it has § § § § § § §http://stackoverflow.com/questions/10776121/what-is-the-unit-of-work-pattern-in-ef §Entity Framework Continue to Bounded slide Bounded Context •Design pattern •Bounded context is context that delimits the applicability of a particular model (one of DDD patterns) •Clearer defined boundaries of each entity or entity group •Better maintainability and less side-effects on context change § § § § § § §https://msdn.microsoft.com/en-us/magazine/jj883952.aspx §Entity Framework There will be no time for this, almost surely. Create at least 4 contexts: •GamesContext – there are only Games in it, used in GamesController •StudioContext – Games, Developers and Studios are present, used in StudiosController •UserContext – there is only user in it as it is completely independent, used in AccountController •SeedingContext – there are all entities in the DB, so seeding is easier. This concept is somewhat finalized in MultipleContextsWithSameEntities.7zip Seeding multiple contexts •Entity Framework is unable to seed multiple contexts with at least one same entity •Thus it is necessary to use single seeding context for development/early testing purposes. •If there are groups of entities without relation between them, it is possible to have multiple seeding contexts that do not interfere with eath other. •Such context(s) should however never been used in any life environment. •Non-seeding context can overlap freely and may even inherit one another •These context should not use any agressive initializer (such as DropCreateDatabaseAlways) •It is no problem for these contexts to exists in single database • • • §http://stackoverflow.com/a/21538091/1138663 § § §Entity Framework Resources •https://app.pluralsight.com/library/courses/entity-framework5-getting-started • •https://app.pluralsight.com/library/courses/entity-framework-6-ninja-edition-whats-new • • • § §Entity Framework https://dev.mysql.com/doc/connector-net/en/connector-net-entityframework60.html