.NET Core + ASP.NET Core Training Course Session 13
.NET Core What we learned? Session 6 ~ 13 Overview • ASP.NET Core Basics • Middleware, Controllers, Action Filters and Routing • Models • Views
.NET Core What we’ll learn today? Session 13 Agenda • Getting started with Entity Framework Core
.NET Core Introduction to Entity Framework Core Entity Framework Core – Intro What is Entity Framework? The Microsoft ADO.NET Entity Framework is an Object/Relational Mapping (ORM) framework that enables developers to work with relational data as domain-specific objects, eliminating the need for most of the data access plumbing code that developers usually need to write. Using the Entity Framework, developers issue queries using LINQ, then retrieve and manipulate data as strongly typed objects. Note: EF Core 1.0 is the latest version of EF but does not yet have all the features of EF 6.x.
.NET Core Introduction to Entity Framework Core Entity Framework Core – Intro What is O/RM? ORM is a tool for storing data from domain objects to relational database like MS SQL Server, in an automated way, without much programming. O/RM includes three main parts: Domain class objects, Relational database objects and Mapping information on how domain objects map to relational database objects (tables, views & storedprocedures). ORM allows us to keep our database design separate from our domain class design. This makes the application maintainable and extendable. It also automates standard CRUD operation (Create, Read, Update & Delete) so that the developer doesn't need to write it manually.
.NET Core Introduction to Entity Framework Core Entity Framework Core – Intro Entity Framework (EF) Core is a lightweight and extensible version of the popular Entity Framework data access technology. Get Entity Framework Core PM> Install-Package Microsoft.EntityFrameworkCore.SqlServer
.NET Core The Model Entity Framework Core – Intro With EF Core, data access is performed using a model. A model is made up of entity classes and a derived context that represents a session with the database, allowing you to query and save data. You can generate a model from an existing database, hand code a model to match your database, or use EF Migrations to create a database from your model (and evolve it as your model changes over time).
.NET Core Basic Model Sample Entity Framework Core – Intro
.NET Core Basic Model Sample Entity Framework Core – Intro Saving Data Querying
.NET Core Creating a Model Entity Framework Core – Model Entity Framework uses a set of conventions to build a model based on the shape of your entity classes. You can specify additional configuration to supplement and/or override what was discovered by convention.
.NET Core Creating a Model Entity Framework Core – Model Methods of configuration • Fluent API You can override the OnModelCreating method in your derived context and use the ModelBuilder API to configure your model. This is the most powerful method of configuration and allows configuration to be specified without modifying your entity classes. Fluent API configuration has the highest precedence and will override conventions and data annotations.
.NET Core Creating a Model Entity Framework Core – Model Methods of configuration • Fluent API
.NET Core Creating a Model Entity Framework Core – Model Methods of configuration • Data Annotations You can also apply attributes (known as Data Annotations) to your classes and properties. Data annotations will override conventions, but will be overwritten by Fluent API configuration.
.NET Core Including & Excluding Types Entity Framework Core – Model Including a type in the model means that EF has metadata about that type and will attempt to read and write instances from/to the database. Conventions By convention, types that are exposed in DbSet properties on your context are included in your model. In addition, types that are mentioned in the OnModelCreating method are also included. Finally, any types that are found by recursively exploring the navigation properties of discovered types are also included in the model.
.NET Core Including & Excluding Types Entity Framework Core – Model For example, in the following code listing all three types are discovered: • Blog because it is exposed in a DbSet property on the context • Post because it is discovered via the Blog.Posts navigation property • AuditEntry because it is mentioned in OnModelCreating
.NET Core Including & Excluding Types Entity Framework Core – Model
.NET Core Including & Excluding Types Entity Framework Core – Model Data Annotations You can use Data Annotations to exclude a type from the model. Fluent API You can use the Fluent API to exclude a type from the model.
.NET Core Including & Excluding Properties Entity Framework Core – Model Including a property in the model means that EF has metadata about that property and will attempt to read and write values from/to the database. Conventions By convention, public properties with a getter and a setter will be included in the model.
.NET Core Keys (primary) Entity Framework Core – Model A key serves as the primary unique identifier for each entity instance. When using a relational database this maps to the concept of a primary key. You can also configure a unique identifier that is not the primary key (see Alternate Keys for more information). Conventions By convention, a property named Id or <type name>Id will be configured as the key of an entity.
.NET Core Keys (primary) Entity Framework Core – Model DataAnnotationsFluentAPI
.NET Core Keys (primary) Entity Framework Core – Model You can also use the Fluent API to configure multiple properties to be the key of an entity (known as a composite key). Composite keys can only be configured using the Fluent API - conventions will never setup a composite key and you can not use Data Annotations to configure one.
.NET Core Generated Properties Entity Framework Core – Model Value Generation Patterns [There are three value generation patterns that can be used for properties.] 1. No value generation No value generation means that you will always supply a valid value to be saved to the database. This valid value must be assigned to new entities before they are added to the context.
.NET Core Generated Properties Entity Framework Core – Model 2. Value generated on add Value generated on add means that a value is generated for new entities. How the value is generated for added entities will depend on the database provider being used. Database providers may automatically setup value generation for some property types, but others may require you to manually setup how the value is generated. If you add an entity to the context that has a value assigned to the primary key property, then EF will attempt to insert that value rather than generating a new one. A property is considered to have a value assigned if it is not assigned the CLR default value (null for string, 0 for int, Guid.Empty for Guid, etc.).
.NET Core Generated Properties Entity Framework Core – Model 2. Value generated on add If the value is generated by the database, then EF may assign a temporary value when you add the entity to the context. This temporary value will then be replaced by the database generated value during SaveChanges.
.NET Core Generated Properties Entity Framework Core – Model 3. Value generated on add or update Value generated on add or update means that a new value is generated every time the record is saved (insert or update). Like ‘value generated on add’, if you specify a value for the property on a newly added instance of an entity, that value will be inserted rather than a value being generated. Also, if you explicitly change the value assigned to the property (thus marking it as modified) then that new value will be set in the database rather than a value being generated.
.NET Core Generated Properties - Conventions Entity Framework Core – Model By convention, primary keys that are of an integer or GUID data type will be setup to have values generated on add. All other properties will be setup with no value generation. No value generation (Data Annotations) Value generated on add (Data Annotations)
.NET Core Generated Properties – Data Annotation, Fluent API Entity Framework Core – Model
.NET Core Generated Properties – Data Annotation, Fluent API Entity Framework Core – Model Value generated on add or update (Fluent API) Value generated on add (Fluent API)
.NET Core Required/optional properties Entity Framework Core – Model Conventions By convention, a property whose CLR type can contain null will be configured as optional (string, int?, byte[], etc.). Properties whose CLR type cannot contain null will be configured as required (int, decimal, bool, etc.). A property is considered optional if it is valid for it to contain null. If null is not a valid value to be assigned to a property then it is considered to be a required property.
.NET Core Required/optional properties Entity Framework Core – Model
.NET Core Maximum Length Entity Framework Core – Model Configuring a maximum length provides a hint to the data store about the appropriate data type to use for a given property. Maximum length only applies to array data types, such as string and byte[]. Entity Framework does not do any validation of maximum length before passing data to the provider. Microsoft SQL Server will use nvarchar(max) for string properties (or nvarchar(450) if the column is used as a key).
.NET Core Maximum Length Entity Framework Core – Model
.NET Core Concurrency Tokens Entity Framework Core – Model If a property is configured as a concurrency token then EF will check that no other user has modified that value in the database when saving changes to that record. EF uses an optimistic concurrency pattern, meaning it will assume the value has not changed and try to save the data, but throw if it finds the value has been changed.
.NET Core Concurrency Tokens Entity Framework Core – Model Data stores can enforce concurrency tokens by checking that any record being updated or deleted still has the same value for the concurrency token that was assigned when the context originally loaded the data from the database. For example, relational database achieve this by including the concurrency token in the WHERE clause of any UPDATE or DELETE commands and checking the number of rows that were affected. If the concurrency token still matches then one row will be updated. If the value in the database has changed, then no rows are updated.
.NET Core Concurrency Tokens Entity Framework Core – Model UPDATE [Person] SET [FirstName] = @p1 WHERE [PersonId] = @p0 AND [LastName] = @p2; Conventions By convention, properties are never configured as concurrency tokens.
.NET Core Concurrency Tokens - Timestamp/row version Entity Framework Core – Model A timestamp is a property where a new value is generated by the database every time a row is inserted or updated. The property is also treated as a concurrency token. This ensures you will get an exception if anyone else has modified a row that you are trying to update since you queried for the data. How this is achieved is up to the database provider being used. For SQL Server, timestamp is usually used on a byte[] property, which will be setup as a ROWVERSION column in the database.
.NET Core Concurrency Tokens - Timestamp/row version Entity Framework Core – Model
.NET Core Shadow Properties Entity Framework Core – Model Shadow properties are properties that do not exist in your entity class. The value and state of these properties is maintained purely in the Change Tracker. Shadow property values can be obtained and changed through the ChangeTracker API. context.Entry(myBlog).Property("LastUpdated").CurrentValue = DateTime.Now; var blogs = context.Blogs .OrderBy(b => EF.Property<DateTime>(b, "LastUpdated"));
.NET Core Shadow Properties - Conventions Entity Framework Core – Model By convention, shadow properties are only created when a relationship is discovered but no foreign key property is found in the dependent entity class. In this case, a shadow foreign key property will be introduced with the name <principal type name><principal key property name>.
.NET Core Shadow Properties - Conventions Entity Framework Core – Model For example, the following code listing will result in a BlogBlogId shadow property being introduced to the Post entity.
.NET Core Shadow Properties – Data Annotation, Fluent API Entity Framework Core – Model Data Annotations: Shadow properties can not be created with data annotations. Fluent API: You can use the Fluent API to configure shadow properties. Once you have called the string overload of Property you can chain any of the configuration calls you would for other properties. If the name supplied to the Property method matches the name of an existing property (a shadow property or one defined on the entity class), then the code will configure that existing property rather than introducing a new shadow property.
.NET Core Shadow Properties – Data Annotation, Fluent API Entity Framework Core – Model
.NET Core Demo Demo

.NET Core, ASP.NET Core Course, Session 13

  • 1.
    .NET Core +ASP.NET Core Training Course Session 13
  • 2.
    .NET Core What welearned? Session 6 ~ 13 Overview • ASP.NET Core Basics • Middleware, Controllers, Action Filters and Routing • Models • Views
  • 3.
    .NET Core What we’lllearn today? Session 13 Agenda • Getting started with Entity Framework Core
  • 4.
    .NET Core Introduction toEntity Framework Core Entity Framework Core – Intro What is Entity Framework? The Microsoft ADO.NET Entity Framework is an Object/Relational Mapping (ORM) framework that enables developers to work with relational data as domain-specific objects, eliminating the need for most of the data access plumbing code that developers usually need to write. Using the Entity Framework, developers issue queries using LINQ, then retrieve and manipulate data as strongly typed objects. Note: EF Core 1.0 is the latest version of EF but does not yet have all the features of EF 6.x.
  • 5.
    .NET Core Introduction toEntity Framework Core Entity Framework Core – Intro What is O/RM? ORM is a tool for storing data from domain objects to relational database like MS SQL Server, in an automated way, without much programming. O/RM includes three main parts: Domain class objects, Relational database objects and Mapping information on how domain objects map to relational database objects (tables, views & storedprocedures). ORM allows us to keep our database design separate from our domain class design. This makes the application maintainable and extendable. It also automates standard CRUD operation (Create, Read, Update & Delete) so that the developer doesn't need to write it manually.
  • 6.
    .NET Core Introduction toEntity Framework Core Entity Framework Core – Intro Entity Framework (EF) Core is a lightweight and extensible version of the popular Entity Framework data access technology. Get Entity Framework Core PM> Install-Package Microsoft.EntityFrameworkCore.SqlServer
  • 7.
    .NET Core The Model EntityFramework Core – Intro With EF Core, data access is performed using a model. A model is made up of entity classes and a derived context that represents a session with the database, allowing you to query and save data. You can generate a model from an existing database, hand code a model to match your database, or use EF Migrations to create a database from your model (and evolve it as your model changes over time).
  • 8.
    .NET Core Basic ModelSample Entity Framework Core – Intro
  • 9.
    .NET Core Basic ModelSample Entity Framework Core – Intro Saving Data Querying
  • 10.
    .NET Core Creating aModel Entity Framework Core – Model Entity Framework uses a set of conventions to build a model based on the shape of your entity classes. You can specify additional configuration to supplement and/or override what was discovered by convention.
  • 11.
    .NET Core Creating aModel Entity Framework Core – Model Methods of configuration • Fluent API You can override the OnModelCreating method in your derived context and use the ModelBuilder API to configure your model. This is the most powerful method of configuration and allows configuration to be specified without modifying your entity classes. Fluent API configuration has the highest precedence and will override conventions and data annotations.
  • 12.
    .NET Core Creating aModel Entity Framework Core – Model Methods of configuration • Fluent API
  • 13.
    .NET Core Creating aModel Entity Framework Core – Model Methods of configuration • Data Annotations You can also apply attributes (known as Data Annotations) to your classes and properties. Data annotations will override conventions, but will be overwritten by Fluent API configuration.
  • 14.
    .NET Core Including &Excluding Types Entity Framework Core – Model Including a type in the model means that EF has metadata about that type and will attempt to read and write instances from/to the database. Conventions By convention, types that are exposed in DbSet properties on your context are included in your model. In addition, types that are mentioned in the OnModelCreating method are also included. Finally, any types that are found by recursively exploring the navigation properties of discovered types are also included in the model.
  • 15.
    .NET Core Including &Excluding Types Entity Framework Core – Model For example, in the following code listing all three types are discovered: • Blog because it is exposed in a DbSet property on the context • Post because it is discovered via the Blog.Posts navigation property • AuditEntry because it is mentioned in OnModelCreating
  • 16.
    .NET Core Including &Excluding Types Entity Framework Core – Model
  • 17.
    .NET Core Including &Excluding Types Entity Framework Core – Model Data Annotations You can use Data Annotations to exclude a type from the model. Fluent API You can use the Fluent API to exclude a type from the model.
  • 18.
    .NET Core Including &Excluding Properties Entity Framework Core – Model Including a property in the model means that EF has metadata about that property and will attempt to read and write values from/to the database. Conventions By convention, public properties with a getter and a setter will be included in the model.
  • 19.
    .NET Core Keys (primary) EntityFramework Core – Model A key serves as the primary unique identifier for each entity instance. When using a relational database this maps to the concept of a primary key. You can also configure a unique identifier that is not the primary key (see Alternate Keys for more information). Conventions By convention, a property named Id or <type name>Id will be configured as the key of an entity.
  • 20.
    .NET Core Keys (primary) EntityFramework Core – Model DataAnnotationsFluentAPI
  • 21.
    .NET Core Keys (primary) EntityFramework Core – Model You can also use the Fluent API to configure multiple properties to be the key of an entity (known as a composite key). Composite keys can only be configured using the Fluent API - conventions will never setup a composite key and you can not use Data Annotations to configure one.
  • 22.
    .NET Core Generated Properties EntityFramework Core – Model Value Generation Patterns [There are three value generation patterns that can be used for properties.] 1. No value generation No value generation means that you will always supply a valid value to be saved to the database. This valid value must be assigned to new entities before they are added to the context.
  • 23.
    .NET Core Generated Properties EntityFramework Core – Model 2. Value generated on add Value generated on add means that a value is generated for new entities. How the value is generated for added entities will depend on the database provider being used. Database providers may automatically setup value generation for some property types, but others may require you to manually setup how the value is generated. If you add an entity to the context that has a value assigned to the primary key property, then EF will attempt to insert that value rather than generating a new one. A property is considered to have a value assigned if it is not assigned the CLR default value (null for string, 0 for int, Guid.Empty for Guid, etc.).
  • 24.
    .NET Core Generated Properties EntityFramework Core – Model 2. Value generated on add If the value is generated by the database, then EF may assign a temporary value when you add the entity to the context. This temporary value will then be replaced by the database generated value during SaveChanges.
  • 25.
    .NET Core Generated Properties EntityFramework Core – Model 3. Value generated on add or update Value generated on add or update means that a new value is generated every time the record is saved (insert or update). Like ‘value generated on add’, if you specify a value for the property on a newly added instance of an entity, that value will be inserted rather than a value being generated. Also, if you explicitly change the value assigned to the property (thus marking it as modified) then that new value will be set in the database rather than a value being generated.
  • 26.
    .NET Core Generated Properties- Conventions Entity Framework Core – Model By convention, primary keys that are of an integer or GUID data type will be setup to have values generated on add. All other properties will be setup with no value generation. No value generation (Data Annotations) Value generated on add (Data Annotations)
  • 27.
    .NET Core Generated Properties– Data Annotation, Fluent API Entity Framework Core – Model
  • 28.
    .NET Core Generated Properties– Data Annotation, Fluent API Entity Framework Core – Model Value generated on add or update (Fluent API) Value generated on add (Fluent API)
  • 29.
    .NET Core Required/optional properties EntityFramework Core – Model Conventions By convention, a property whose CLR type can contain null will be configured as optional (string, int?, byte[], etc.). Properties whose CLR type cannot contain null will be configured as required (int, decimal, bool, etc.). A property is considered optional if it is valid for it to contain null. If null is not a valid value to be assigned to a property then it is considered to be a required property.
  • 30.
  • 31.
    .NET Core Maximum Length EntityFramework Core – Model Configuring a maximum length provides a hint to the data store about the appropriate data type to use for a given property. Maximum length only applies to array data types, such as string and byte[]. Entity Framework does not do any validation of maximum length before passing data to the provider. Microsoft SQL Server will use nvarchar(max) for string properties (or nvarchar(450) if the column is used as a key).
  • 32.
    .NET Core Maximum Length EntityFramework Core – Model
  • 33.
    .NET Core Concurrency Tokens EntityFramework Core – Model If a property is configured as a concurrency token then EF will check that no other user has modified that value in the database when saving changes to that record. EF uses an optimistic concurrency pattern, meaning it will assume the value has not changed and try to save the data, but throw if it finds the value has been changed.
  • 34.
    .NET Core Concurrency Tokens EntityFramework Core – Model Data stores can enforce concurrency tokens by checking that any record being updated or deleted still has the same value for the concurrency token that was assigned when the context originally loaded the data from the database. For example, relational database achieve this by including the concurrency token in the WHERE clause of any UPDATE or DELETE commands and checking the number of rows that were affected. If the concurrency token still matches then one row will be updated. If the value in the database has changed, then no rows are updated.
  • 35.
    .NET Core Concurrency Tokens EntityFramework Core – Model UPDATE [Person] SET [FirstName] = @p1 WHERE [PersonId] = @p0 AND [LastName] = @p2; Conventions By convention, properties are never configured as concurrency tokens.
  • 36.
    .NET Core Concurrency Tokens- Timestamp/row version Entity Framework Core – Model A timestamp is a property where a new value is generated by the database every time a row is inserted or updated. The property is also treated as a concurrency token. This ensures you will get an exception if anyone else has modified a row that you are trying to update since you queried for the data. How this is achieved is up to the database provider being used. For SQL Server, timestamp is usually used on a byte[] property, which will be setup as a ROWVERSION column in the database.
  • 37.
    .NET Core Concurrency Tokens- Timestamp/row version Entity Framework Core – Model
  • 38.
    .NET Core Shadow Properties EntityFramework Core – Model Shadow properties are properties that do not exist in your entity class. The value and state of these properties is maintained purely in the Change Tracker. Shadow property values can be obtained and changed through the ChangeTracker API. context.Entry(myBlog).Property("LastUpdated").CurrentValue = DateTime.Now; var blogs = context.Blogs .OrderBy(b => EF.Property<DateTime>(b, "LastUpdated"));
  • 39.
    .NET Core Shadow Properties- Conventions Entity Framework Core – Model By convention, shadow properties are only created when a relationship is discovered but no foreign key property is found in the dependent entity class. In this case, a shadow foreign key property will be introduced with the name <principal type name><principal key property name>.
  • 40.
    .NET Core Shadow Properties- Conventions Entity Framework Core – Model For example, the following code listing will result in a BlogBlogId shadow property being introduced to the Post entity.
  • 41.
    .NET Core Shadow Properties– Data Annotation, Fluent API Entity Framework Core – Model Data Annotations: Shadow properties can not be created with data annotations. Fluent API: You can use the Fluent API to configure shadow properties. Once you have called the string overload of Property you can chain any of the configuration calls you would for other properties. If the name supplied to the Property method matches the name of an existing property (a shadow property or one defined on the entity class), then the code will configure that existing property rather than introducing a new shadow property.
  • 42.
    .NET Core Shadow Properties– Data Annotation, Fluent API Entity Framework Core – Model
  • 43.