29 Nisan 2019

fluent api

https://www.tutorialspoint.com/entity_framework/entity_framework_fluent_api.htm


Fluent API is an advanced way of specifying model configuration that covers everything that data annotations can do in addition to some more advanced configuration not possible with data annotations. Data annotations and the fluent API can be used together, but Code First gives precedence to Fluent API > data annotations > default conventions.
  • Fluent API is another way to configure your domain classes.
  • The Code First Fluent API is most commonly accessed by overriding the OnModelCreating method on your derived DbContext.
  • Fluent API provides more functionality for configuration than DataAnnotations. Fluent API supports the following types of mappings.
In this chapter, we will continue with the simple example which contains Student, Course and Enrollment classes and one context class with MyContext name as shown in the following code.
using System.Data.Entity; 
using System.Linq; 
using System.Text;
using System.Threading.Tasks;  

namespace EFCodeFirstDemo {

   class Program {
      static void Main(string[] args) {}
   }
   
   public enum Grade {
      A, B, C, D, F
   }

   public class Enrollment {
      public int EnrollmentID { get; set; }
      public int CourseID { get; set; }
      public int StudentID { get; set; }
      public Grade? Grade { get; set; }
  
      public virtual Course Course { get; set; }
      public virtual Student Student { get; set; }
   }

   public class Student {
      public int ID { get; set; }
      public string LastName { get; set; }
      public string FirstMidName { get; set; }
  
      public DateTime EnrollmentDate { get; set; }
  
      public virtual ICollection<Enrollment> Enrollments { get; set; }
   }

   public class Course {
      public int CourseID { get; set; }
      public string Title { get; set; }
      public int Credits { get; set; }
  
      public virtual ICollection<Enrollment> Enrollments { get; set; }
   }

   public class MyContext : DbContext {
      public virtual DbSet<Course> Courses { get; set; }
      public virtual DbSet<Enrollment> Enrollments { get; set; }
      public virtual DbSet<Student> Students { get; set; }
   }

}   
To access Fluent API you need to override the OnModelCreating method in DbContext. Let’s take a look at a simple example in which we will rename the column name in student table from FirstMidName to FirstName as shown in the following code.
public class MyContext : DbContext {

   protected override void OnModelCreating(DbModelBuilder modelBuilder) {
      modelBuilder.Entity<Student>().Property(s  s.FirstMidName)
      .HasColumnName("FirstName");}

      public virtual DbSet<Course> Courses { get; set; }
      public virtual DbSet<Enrollment> Enrollments { get; set; }
      public virtual DbSet<Student> Students { get; set; }
}
DbModelBuilder is used to map CLR classes to a database schema. It is the main class and on which you can configure all your domain classes. This code centric approach to building an Entity Data Model (EDM) is known as Code First.
Fluent API provides a number of important methods to configure entities and its properties to override various Code First conventions. Below are some of them.

------------------------------------------------------

Fluent API lets you configure your entities or their properties, whether you want to change something about how they map to the database or how they relate to one another. There's a huge variety of mappings and modeling that you can impact using the configurations. Following are the main types of mapping which Fluent API supports −
  • Entity Mapping
  • Properties Mapping

Entity Mapping

Entity mapping is just some simple mappings that will impact Entity Framework's understanding of how the classes are mapped to the databases. All these we discussed in data annotations and here we will see how to achieve the same things using Fluent API.
  • So rather than going into the domain classes to add these configurations, we can do this inside of the context.
  • The first thing is to override the OnModelCreating method, which gives the modelBuilder to work with.

Default Schema

The default schema is dbo when the database is generated. You can use the HasDefaultSchema method on DbModelBuilder to specify the database schema to use for all tables, stored procedures, etc.
Let’s take a look at the following example in which admin schema is applied.
public class MyContext : DbContext {
   public MyContext() : base("name = MyContextDB") {}

   protected override void OnModelCreating(DbModelBuilder modelBuilder) {
      //Configure default schema
      modelBuilder.HasDefaultSchema("Admin");
   }
 
   public virtual DbSet<Course> Courses { get; set; }
   public virtual DbSet<Enrollment> Enrollments { get; set; }
   public virtual DbSet<Student> Students { get; set; }
}

Map Entity to Table

With default convention, Code First will create the database tables with the name of DbSet properties in the context class such as Courses, Enrollments and Students. But if you want different table names then you can override this convention and can provide a different table name than the DbSet properties, as shown in the following code.
protected override void OnModelCreating(DbModelBuilder modelBuilder) {

   //Configure default schema
   modelBuilder.HasDefaultSchema("Admin");

   //Map entity to table
   modelBuilder.Entity<Student>().ToTable("StudentData");
   modelBuilder.Entity<Course>().ToTable("CourseDetail");
   modelBuilder.Entity<Enrollment>().ToTable("EnrollmentInfo");
}
When the database is generated, you will see the tables name as specified in the OnModelCreating method.
OnModel Method

Entity Splitting (Map Entity to Multiple Table)

Entity Splitting lets you combine data coming from multiple tables into a single class and it can only be used with tables that have a one-to-one relationship between them. Let’s take a look at the following example in which Student information is mapped into two tables.
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
   //Configure default schema
   modelBuilder.HasDefaultSchema("Admin");

   //Map entity to table
   modelBuilder.Entity<Student>().Map(sd  {
      sd.Properties(p  new { p.ID, p.FirstMidName, p.LastName });
      sd.ToTable("StudentData");
   })

   .Map(si  {
      si.Properties(p  new { p.ID, p.EnrollmentDate });
      si.ToTable("StudentEnrollmentInfo");
   });

   modelBuilder.Entity<Course>().ToTable("CourseDetail");
   modelBuilder.Entity<Enrollment>().ToTable("EnrollmentInfo");
}
In the above code, you can see that Student entity is split into the following two tables by mapping some properties to StudentData table and some properties to StudentEnrollmentInfo table using Map method.
  • StudentData − Contains Student FirstMidName and Last Name.
  • StudentEnrollmentInfo − Contains EnrollmentDate.
When the database is generated you see the following tables in your database as shown in the following image.
Entity Splitting

Properties Mapping

The Property method is used to configure attributes for each property belonging to an entity or complex type. The Property method is used to obtain a configuration object for a given property. You can also map and configure the properties of your domain classes using Fluent API.

Configuring a Primary Key

The default convention for primary keys are −
  • Class defines a property whose name is “ID” or “Id”
  • Class name followed by “ID” or “Id”
If your class doesn’t follow the default conventions for primary key as shown in the following code of Student class −
public class Student {
   public int StdntID { get; set; }
   public string LastName { get; set; }
   public string FirstMidName { get; set; }
   public DateTime EnrollmentDate { get; set; }
 
   public virtual ICollection<Enrollment> Enrollments { get; set; }
}
Then to explicitly set a property to be a primary key, you can use the HasKey method as shown in the following code −
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
   //Configure default schema
   modelBuilder.HasDefaultSchema("Admin");
 
   // Configure Primary Key
   modelBuilder.Entity<Student>().HasKey(s  s.StdntID); 
}

Hiç yorum yok: