Entity Framework Notes For Professionals. 80+ pages of professional hints and tricks (GoalKicker.com) (Z-Library)

Author: GoalKicker.com

非小说

No Description

📄 File Format: PDF
💾 File Size: 1.5 MB
41
Views
0
Downloads
0.00
Total Donations

📄 Text Preview (First 20 pages)

ℹ️

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

📄 Page 1
Entity Framework Notes for ProfessionalsEntity Framework Notes for Professionals GoalKicker.com Free Programming Books Disclaimer This is an unocial free book created for educational purposes and is not aliated with ocial Entity Framework group(s) or company(s). All trademarks and registered trademarks are the property of their respective owners 80+ pages of professional hints and tricks
📄 Page 2
Contents About 1 ................................................................................................................................................................................... Chapter 1: Getting started with Entity Framework 2 ..................................................................................... Section 1.1: Installing the Entity Framework NuGet Package 2 .................................................................................... Section 1.2: Using Entity Framework from C# (Code First) 4 ....................................................................................... Section 1.3: What is Entity Framework? 5 ....................................................................................................................... Chapter 2: Code First Conventions 6 ...................................................................................................................... Section 2.1: Removing Conventions 6 ............................................................................................................................. Section 2.2: Primary Key Convention 6 .......................................................................................................................... Section 2.3: Type Discovery 6 ......................................................................................................................................... Section 2.4: DecimalPropertyConvention 7 ................................................................................................................... Section 2.5: Relationship Convention 9 .......................................................................................................................... Section 2.6: Foreign Key Convention 10 ........................................................................................................................ Chapter 3: Code First DataAnnotations 11 .......................................................................................................... Section 3.1: [Column] attribute 11 ................................................................................................................................... Section 3.2: [DatabaseGenerated] attribute 11 ............................................................................................................ Section 3.3: [Required] attribute 12 ................................................................................................................................ Section 3.4: [MaxLength] and [MinLength] attributes 12 ............................................................................................ Section 3.5: [InverseProperty(string)] attribute 13 ....................................................................................................... Section 3.6: [ComplexType] attribute 14 ....................................................................................................................... Section 3.7: [ForeignKey(string)] attribute 15 ............................................................................................................... Section 3.8: [Range(min,max)] attribute 15 .................................................................................................................. Section 3.9: [NotMapped] attribute 16 ........................................................................................................................... Section 3.10: [Table] attribute 17 .................................................................................................................................... Section 3.11: [Index] attribute 17 ..................................................................................................................................... Section 3.12: [Key] attribute 18 ....................................................................................................................................... Section 3.13: [StringLength(int)] attribute 19 ................................................................................................................. Section 3.14: [Timestamp] attribute 19 .......................................................................................................................... Section 3.15: [ConcurrencyCheck] Attribute 20 ............................................................................................................. Chapter 4: Entity Framework Code First 21 ....................................................................................................... Section 4.1: Connect to an existing database 21 ........................................................................................................... Chapter 5: Entity framework Code First Migrations 23 ................................................................................ Section 5.1: Enable Migrations 23 .................................................................................................................................... Section 5.2: Add your first migration 23 ........................................................................................................................ Section 5.3: Doing "Update-Database" within your code 25 ....................................................................................... Section 5.4: Seeding Data during migrations 25 ........................................................................................................... Section 5.5: Initial Entity Framework Code First Migration Step by Step 26 .............................................................. Section 5.6: Using Sql() during migrations 27 ............................................................................................................... Chapter 6: Inheritance with EntityFramework (Code First) 29 .................................................................. Section 6.1: Table per hierarchy 29 ................................................................................................................................. Section 6.2: Table per type 29 ......................................................................................................................................... Chapter 7: Code First - Fluent API 31 ...................................................................................................................... Section 7.1: Mapping models 31 ...................................................................................................................................... Section 7.2: Composite Primary Key 32 ......................................................................................................................... Section 7.3: Maximum Length 33 .................................................................................................................................... Section 7.4: Primary Key 33 ............................................................................................................................................ Section 7.5: Required properties (NOT NULL) 34 ..........................................................................................................
📄 Page 3
Section 7.6: Explict Foreign Key naming 34 ................................................................................................................... Chapter 8: Mapping relationship with Entity Framework Code First: One-to-one and variations 36 ........................................................................................................................................................................ Section 8.1: Mapping one-to-zero or one 36 .................................................................................................................. Section 8.2: Mapping one-to-one 39 .............................................................................................................................. Section 8.3: Mapping one or zero-to-one or zero 40 .................................................................................................... Chapter 9: Mapping relationship with Entity Framework Code First: One-to-many and Many-to-many 41 ............................................................................................................................................................. Section 9.1: Mapping one-to-many 41 ............................................................................................................................ Section 9.2: Mapping one-to-many: against the convention 42 ................................................................................. Section 9.3: Mapping zero or one-to-many 43 .............................................................................................................. Section 9.4: Many-to-many 44 ........................................................................................................................................ Section 9.5: Many-to-many: customizing the join table 45 .......................................................................................... Section 9.6: Many-to-many: custom join entity 46 ....................................................................................................... Chapter 10: Database first model generation 49 ............................................................................................. Section 10.1: Generating model from database 49 ....................................................................................................... Section 10.2: Adding data annotations to the generated model 50 ........................................................................... Chapter 11: Complex Types 52 .................................................................................................................................... Section 11.1: Code First Complex Types 52 ..................................................................................................................... Chapter 12: Database Initialisers 53 ........................................................................................................................ Section 12.1: CreateDatabaseIfNotExists 53 ................................................................................................................... Section 12.2: DropCreateDatabaseIfModelChanges 53 ............................................................................................... Section 12.3: DropCreateDatabaseAlways 53 ............................................................................................................... Section 12.4: Custom database initializer 53 .................................................................................................................. Section 12.5: MigrateDatabaseToLatestVersion 54 ...................................................................................................... Chapter 13: Tracking vs. No-Tracking 55 .............................................................................................................. Section 13.1: No-tracking queries 55 ............................................................................................................................... Section 13.2: Tracking queries 55 .................................................................................................................................... Section 13.3: Tracking and projections 55 ...................................................................................................................... Chapter 14: Transactions 57 ....................................................................................................................................... Section 14.1: Database.BeginTransaction() 57 ............................................................................................................... Chapter 15: Managing entity state 58 .................................................................................................................... Section 15.1: Setting state Added of a single entity 58 .................................................................................................. Section 15.2: Setting state Added of an object graph 58 ............................................................................................. Chapter 16: Loading related entities 60 ................................................................................................................ Section 16.1: Eager loading 60 ......................................................................................................................................... Section 16.2: Explicit loading 60 ....................................................................................................................................... Section 16.3: Lazy loading 61 ........................................................................................................................................... Section 16.4: Projection Queries 61 ................................................................................................................................. Chapter 17: Model Restraints 63 ................................................................................................................................ Section 17.1: One-to-many relationships 63 ................................................................................................................... Chapter 18: Entity Framework with PostgreSQL 65 ........................................................................................ Section 18.1: Pre-Steps needed in order to use Entity Framework 6.1.3 with PostgresSql using Npgsqlddexprovider 65 ........................................................................................................................................... Chapter 19: Entity Framework with SQLite 66 .................................................................................................... Section 19.1: Setting up a project to use Entity Framework with an SQLite provider 66 ........................................... Chapter 20: .t4 templates in entity framework 69 ......................................................................................... Section 20.1: Dynamically adding Interfaces to model 69 ...........................................................................................
📄 Page 4
Section 20.2: Adding XML Documentation to Entity Classes 69 .................................................................................. Chapter 21: Advanced mapping scenarios: entity splitting, table splitting 71 .................................. Section 21.1: Entity splitting 71 ......................................................................................................................................... Section 21.2: Table splitting 72 ........................................................................................................................................ Chapter 22: Best Practices For Entity Framework (Simple & Professional) 73 ................................. Section 22.1: 1- Entity Framework @ Data layer (Basics) 73 ....................................................................................... Section 22.2: 2- Entity Framework @ Business layer 76 .............................................................................................. Section 22.3: 3- Using Business layer @ Presentation layer (MVC) 79 ....................................................................... Section 22.4: 4- Entity Framework @ Unit Test Layer 81 ............................................................................................ Chapter 23: Optimization Techniques in EF 85 ................................................................................................... Section 23.1: Using AsNoTracking 85 .............................................................................................................................. Section 23.2: Execute queries in the database when possible, not in memory 85 .................................................... Section 23.3: Loading Only Required Data 85 ............................................................................................................... Section 23.4: Execute multiple queries async and in parallel 86 ................................................................................. Section 23.5: Working with stub entities 87 ................................................................................................................... Section 23.6: Disable change tracking and proxy generation 88 ............................................................................... Credits 89 .............................................................................................................................................................................. You may also like 90 ........................................................................................................................................................
📄 Page 5
GoalKicker.com – Entity Framework Notes for Professionals 1 About Please feel free to share this PDF with anyone for free, latest version of this book can be downloaded from: https://goalkicker.com/EntityFrameworkBook This Entity Framework Notes for Professionals book is compiled from Stack Overflow Documentation, the content is written by the beautiful people at Stack Overflow. Text content is released under Creative Commons BY-SA, see credits at the end of this book whom contributed to the various chapters. Images may be copyright of their respective owners unless otherwise specified This is an unofficial free book created for educational purposes and is not affiliated with official Entity Framework group(s) or company(s) nor Stack Overflow. All trademarks and registered trademarks are the property of their respective company owners The information presented in this book is not guaranteed to be correct nor accurate, use at your own risk Please send feedback and corrections to web@petercv.com
📄 Page 6
GoalKicker.com – Entity Framework Notes for Professionals 2 Chapter 1: Getting started with Entity Framework Version Release Date 1.0 2008-08-11 4.0 2010-04-12 4.1 2011-04-12 4.1 Update 1 2011-07-25 4.3.1 2012-02-29 5.0 2012-08-11 6.0 2013-10-17 6.1 2014-03-17 Core 1.0 2016-06-27 Release Notes: https://msdn.microsoft.com/en-ca/data/jj574253.aspx Section 1.1: Installing the Entity Framework NuGet Package In your Visual Studio open the Solution Explorer window then right click on your project then choose Manage NuGet Packages from the menu: In the window that opens type EntityFramework in the search box in the top right.
📄 Page 7
GoalKicker.com – Entity Framework Notes for Professionals 3 Or if you are using Visual Studio 2015 you'll see something like this: Then click Install. We can also install entity framework using the package manager console. To do you have first to open it using the Tools menu -> NuGet Package Manager -> Package Manager Console then enter this:
📄 Page 8
GoalKicker.com – Entity Framework Notes for Professionals 4 Install-Package EntityFramework This will install Entity Framework and automatically add a reference to the assembly in your project. Section 1.2: Using Entity Framework from C# (Code First) Code first allows you to create your entities (classes) without using a GUI designer or a .edmx file. It is named Code first, because you can create your models first and Entity framework will create database according to mappings for you automatically. Or you can also use this approach with existing database, which is called code first with existing database For example, if you want a table to hold a list of planets: public class Planet { public string Name { get; set; } public decimal AverageDistanceFromSun { get; set; } } Now create your context which is the bridge between your entity classes and the database. Give it one or more DbSet<> properties: using System.Data.Entity; public class PlanetContext : DbContext { public DbSet<Planet> Planets { get; set; } } We can use this by doing the following: using(var context = new PlanetContext()) { var jupiter = new Planet {
📄 Page 9
GoalKicker.com – Entity Framework Notes for Professionals 5 Name = "Jupiter", AverageDistanceFromSun = 778.5 }; context.Planets.Add(jupiter); context.SaveChanges(); } In this example we create a new Planet with the Name property with the value of "Jupiter" and the AverageDistanceFromSun property with the value of 778.5 We can then add this Planet to the context by using the DbSet's Add() method and commit our changes to the database by using the SaveChanges() method. Or we can retrieve rows from the database: using(var context = new PlanetContext()) { var jupiter = context.Planets.Single(p => p.Name == "Jupiter"); Console.WriteLine($"Jupiter is {jupiter.AverageDistanceFromSun} million km from the sun."); } Section 1.3: What is Entity Framework? Writing and managing ADO.Net code for data access is a tedious and monotonous job. Microsoft has provided an O/RM framework called "Entity Framework" to automate database related activities for your application. Entity framework is an Object/Relational Mapping (O/RM) framework. It is an enhancement to ADO.NET that gives developers an automated mechanism for accessing & storing the data in the database. What is O/RM? ORM is a tool for storing data from domain objects to the relational database like MS SQL Server, in an automated way, without much programming. O/RM includes three main parts: Domain class objects1. Relational database objects2. Mapping information on how domain objects map to relational database objects(e.x tables, views & stored3. procedures) 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.
📄 Page 10
GoalKicker.com – Entity Framework Notes for Professionals 6 Chapter 2: Code First Conventions Section 2.1: Removing Conventions You can remove any of the conventions defined in the System.Data.Entity.ModelConfiguration.Conventions namespace, by overriding OnModelCreating method. The following example removes PluralizingTableNameConvention. public class EshopContext : DbContext { public DbSet<Product> Products { set; get; } . . . protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); } } By default EF will create DB table with entity class name suffixed by 's'. In this example, Code First is configured to ignore PluralizingTableName convention so, instead of dbo.Products table dbo.Product table will be created. Section 2.2: Primary Key Convention By default a property is a primary key if a property on a class is named “ID” (not case sensitive), or the class name followed by "ID". If the type of the primary key property is numeric or GUID it will be configured as an identity column. Simple Example: public class Room { // Primary key public int RoomId{ get; set; } ... } Section 2.3: Type Discovery By default Code First includes in model Types defined as a DbSet property in context class.1. Reference types included in entity types even if they are defined in different assembly.2. Derived classes even if only the base class is defined as DbSet property3. Here is an example, that we are only adding Company as DbSet<Company> in our context class: public class Company { public int Id { set; get; } public string Name { set; get; } public virtual ICollection<Department> Departments { set; get; } } public class Department { public int Id { set; get; }
📄 Page 11
GoalKicker.com – Entity Framework Notes for Professionals 7 public string Name { set; get; } public virtual ICollection<Person> Staff { set; get; } } [Table("Staff")] public class Person { public int Id { set; get; } public string Name { set; get; } public decimal Salary { set; get; } } public class ProjectManager : Person { public string ProjectManagerProperty { set; get; } } public class Developer : Person { public string DeveloperProperty { set; get; } } public class Tester : Person { public string TesterProperty { set; get; } } public class ApplicationDbContext : DbContext { public DbSet<Company> Companies { set; get; } } We can see that all the classes are included in model Section 2.4: DecimalPropertyConvention By default Entity Framework maps decimal properties to decimal(18,2) columns in database tables.
📄 Page 12
GoalKicker.com – Entity Framework Notes for Professionals 8 public class Box { public int Id { set; get; } public decimal Length { set; get; } public decimal Width { set; get; } public decimal Height { set; get; } } We can change the precision of decimal properties: 1.Use Fluent API: protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Box>().Property(b => b.Width).HasPrecision(20, 4); } Only "Width" Property is mapped to decimal(20, 4). 2.Replace the convention: protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Remove<DecimalPropertyConvention>(); modelBuilder.Conventions.Add(new DecimalPropertyConvention(10, 4)); }
📄 Page 13
GoalKicker.com – Entity Framework Notes for Professionals 9 Every decimal property is mapped to decimal(10,4) columns. Section 2.5: Relationship Convention Code First infer the relationship between the two entities using navigation property. This navigation property can be a simple reference type or collection type. For example, we defined Standard navigation property in Student class and ICollection navigation property in Standard class. So, Code First automatically created one-to-many relationship between Standards and Students DB table by inserting Standard_StandardId foreign key column in the Students table. public class Student { public int StudentID { get; set; } public string StudentName { get; set; } public DateTime DateOfBirth { get; set; } //Navigation property public Standard Standard { get; set; } } public class Standard { public int StandardId { get; set; } public string StandardName { get; set; } //Collection navigation property public IList<Student> Students { get; set; } } The above entities created the following relationship using Standard_StandardId foreign key.
📄 Page 14
GoalKicker.com – Entity Framework Notes for Professionals 10 Section 2.6: Foreign Key Convention If class A is in relationship with class B and class B has property with the same name and type as the primary key of A, then EF automatically assumes that property is foreign key. public class Department { public int DepartmentId { set; get; } public string Name { set; get; } public virtual ICollection<Person> Staff { set; get; } } public class Person { public int Id { set; get; } public string Name { set; get; } public decimal Salary { set; get; } public int DepartmentId { set; get; } public virtual Department Department { set; get; } } In this case DepartmentId is foreign key without explicit specification.
📄 Page 15
GoalKicker.com – Entity Framework Notes for Professionals 11 Chapter 3: Code First DataAnnotations Section 3.1: [Column] attribute public class Person { public int PersonID { get; set; } [Column("NameOfPerson")] public string PersonName { get; set; } } Tells Entity Framework to use a specific column name instead using the name of the property. You can also specify the database data type and the order of the column in table: [Column("NameOfPerson", TypeName = "varchar", Order = 1)] public string PersonName { get; set; } Section 3.2: [DatabaseGenerated] attribute Specifies how the database generates values for the property. There are three possible values: None specifies that the values are not generated by the database.1. Identity specifies that the column is an identity column, which is typically used for integer primary keys.2. Computed specifies that the database generates the value for the column.3. If the value is anything other than None, Entity Framework will not commit changes made to the property back to the database. By default (based on the StoreGeneratedIdentityKeyConvention) an integer key property will be treated as an identity column. To override this convention and force it to be treated as a non-identity column you can use the DatabaseGenerated attribute with a value of None. using System.ComponentModel.DataAnnotations.Schema; public class Foo { [Key] public int Id { get; set; } // identity (auto-increment) column } public class Bar { [Key] [DatabaseGenerated(DatabaseGeneratedOption.None)] public int Id { get; set; } // non-identity column } The following SQL creates a table with a computed column: CREATE TABLE [Person] ( Name varchar(100) PRIMARY KEY, DateOfBirth Date NOT NULL, Age AS DATEDIFF(year, DateOfBirth, GETDATE()) )
📄 Page 16
GoalKicker.com – Entity Framework Notes for Professionals 12 GO To create an entity for representing the records in the above table, you would need to use the DatabaseGenerated attribute with a value of Computed. [Table("Person")] public class Person { [Key, StringLength(100)] public string Name { get; set; } public DateTime DateOfBirth { get; set; } [DatabaseGenerated(DatabaseGeneratedOption.Computed)] public int Age { get; set; } } Section 3.3: [Required] attribute When applied to a property of a domain class, the database will create a NOT NULL column. using System.ComponentModel.DataAnnotations; public class Person { public int PersonID { get; set; } [Required] public string PersonName { get; set; } } The resulting column with the NOT NULL constraint: Note: It can also be used with asp.net-mvc as a validation attribute. Section 3.4: [MaxLength] and [MinLength] attributes [MaxLength(int)] attribute can be applied to a string or array type property of a domain class. Entity Framework will set the size of a column to the specified value. using System.ComponentModel.DataAnnotations; public class Person { public int PersonID { get; set; } [MinLength(3), MaxLength(100)] public string PersonName { get; set; } } The resulting column with the specified column length:
📄 Page 17
GoalKicker.com – Entity Framework Notes for Professionals 13 [MinLength(int)] attribute is a validation attribute, it does not affect the database structure. If we try to insert/update a Person with PersonName with length less than 3 characters, this commit will fail. We’ll get a DbUpdateConcurrencyException that we'll need to handle. using (var db = new ApplicationDbContext()) { db.Staff.Add(new Person() { PersonName = "ng" }); try { db.SaveChanges(); } catch (DbEntityValidationException ex) { //ErrorMessage = "The field PersonName must be a string or array type with a minimum length of '3'." } } Both [MaxLength] and [MinLength] attributes can also be used with asp.net-mvc as a validation attribute. Section 3.5: [InverseProperty(string)] attribute using System.ComponentModel.DataAnnotations.Schema; public class Department { ... public virtual ICollection<Employee> PrimaryEmployees { get; set; } public virtual ICollection<Employee> SecondaryEmployees { get; set; } } public class Employee { ... [InverseProperty("PrimaryEmployees")] public virtual Department PrimaryDepartment { get; set; } [InverseProperty("SecondaryEmployees")] public virtual Department SecondaryDepartment { get; set; } } InverseProperty can be used to identify two way relationships when multiple two way relationships exist between two entities. It tells Entity Framework which navigation properties it should match with properties on the other side. Entity Framework doesn't know which navigation property map with which properties on the other side when multiple bidirectional relationships exist between two entities. It needs the name of the corresponding navigation property in the related class as its parameter.
📄 Page 18
GoalKicker.com – Entity Framework Notes for Professionals 14 This can also be used for entities that have a relationship to other entities of the same type, forming a recursive relationship. using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; public class TreeNode { [Key] public int ID { get; set; } public int ParentID { get; set; } ... [ForeignKey("ParentID")] public TreeNode ParentNode { get; set; } [InverseProperty("ParentNode")] public virtual ICollection<TreeNode> ChildNodes { get; set; } } Note also the use of the ForeignKey attribute to specify the column that is used for the foreign key on the table. In the first example, the two properties on the Employee class could have had the ForeignKey attribute applied to define the column names. Section 3.6: [ComplexType] attribute using System.ComponentModel.DataAnnotations.Schema; [ComplexType] public class BlogDetails { public DateTime? DateCreated { get; set; } [MaxLength(250)] public string Description { get; set; } } public class Blog { ... public BlogDetails BlogDetail { get; set; } } Mark the class as complex type in Entity Framework. Complex Types (Or Value Objects In Domain Driven Design) cannot be tracked on their own but they are tracked as part of an entity. This is why BlogDetails in the example does not have a key property. They can be useful when describing domain entities across multiple classes and layering those classes into a
📄 Page 19
GoalKicker.com – Entity Framework Notes for Professionals 15 complete entity. Section 3.7: [ForeignKey(string)] attribute Specifies custom foreign key name if a foreign key not following EF's convention is desired. public class Person { public int IdAddress { get; set; } [ForeignKey(nameof(IdAddress))] public virtual Address HomeAddress { get; set; } } This can also be used when you have multiple relationships to the same entity type. using System.ComponentModel.DataAnnotations.Schema; public class Customer { ... public int MailingAddressID { get; set; } public int BillingAddressID { get; set; } [ForeignKey("MailingAddressID")] public virtual Address MailingAddress { get; set; } [ForeignKey("BillingAddressID")] public virtual Address BillingAddress { get; set; } } Without the ForeignKey attributes, EF might get them mixed up and use the value of BillingAddressID when fetching the MailingAddress, or it might just come up with a different name for the column based on its own naming conventions (like Address_MailingAddress_Id) and try to use that instead (which would result in an error if you're using this with an existing database). Section 3.8: [Range(min,max)] attribute Specifies a numeric minimum and maximum range for a property using System.ComponentModel.DataAnnotations; public partial class Enrollment { public int EnrollmentID { get; set; } [Range(0, 4)] public Nullable<decimal> Grade { get; set; } } If we try to insert/update a Grade with value out of range, this commit will fail. We’ll get a DbUpdateConcurrencyException that we'll need to handle. using (var db = new ApplicationDbContext()) { db.Enrollments.Add(new Enrollment() { Grade = 1000 });
📄 Page 20
GoalKicker.com – Entity Framework Notes for Professionals 16 try { db.SaveChanges(); } catch (DbEntityValidationException ex) { // Validation failed for one or more entities } } It can also be used with asp.net-mvc as a validation attribute. Result: Section 3.9: [NotMapped] attribute By Code-First convention, Entity Framework creates a column for every public property that is of a supported data type and has both a getter and a setter. [NotMapped] annotation must be applied to any properties that we do NOT want a column in a database table for. An example of a property that we might not want to store in the database is a student’s full name based on their first and last name. That can be calculated on the fly and there is no need to store it in the database. public string FullName => string.Format("{0} {1}", FirstName, LastName); The "FullName" property has only a getter and no setter, so by default, Entity Framework will NOT create a column for it. Another example of a property that we might not want to store in the database is a student’s "AverageGrade". We do not want to get the AverageGrade on-demand; instead we might have a routine elsewhere that calculates it. [NotMapped] public float AverageGrade { set; get; } The "AverageGrade" must be marked [NotMapped] annotation, else Entity Framework will create a column for it. using System.ComponentModel.DataAnnotations.Schema; public class Student { public int Id { set; get; } public string FirstName { set; get; } public string LastName { set; get; } public string FullName => string.Format("{0} {1}", FirstName, LastName); [NotMapped] public float AverageGrade { set; get; } } For the above Entity we will see inside DbMigration.cs
The above is a preview of the first 20 pages. Register to read the complete e-book.

💝 Support Author

0.00
Total Amount (¥)
0
Donation Count

Login to support the author

Login Now
Back to List