Use Entity Framework Fluent API
How to Change Entity Framework Default Conventions, when Mapping Data ?There are 3 ways.
1. Entity Framework Fluent API
2. Fluent Validation
- Validation Library for .NET
- This uses a fluent interface and lambda expressions for building validation rules
for your business objects
3. Data Annotations
What is Entity Framework Fluent API ?
- When working with Entity Framework Code First the default behavior is to map your POCO classes to tables using a set of conventions baked into Entity Framework
- Sometimes, however you cannot or do not want to follow those conventions and need to map entities to something other than what the conventions dictate
- For such a scenario you can use Fluent API
- Can be Used Only with Code First Development
- This is used to define the mapping between your objects and the database
What Does Fluent API do ?
- The Code First Fluent API is most commonly accessed by overriding the OnModelCreating method on your derived DbContext class
Which Tasks can be Achieved by using Fluent API ?
1. Property Mapping
2. Type Mapping
3. Configuring Relationships
3. Configuring Relationships
1. Property Mapping
- is used to configure attributes for each property belonging to an entity or complex type
- is used to obtain a configuration object for a given property
- the options on the configuration object are specific to the type being configured
e.g. IsUnicode is available only on string properties
- How to Configure a Primary Key ?
- The HasKey method is used to configure the InstructorID primary key on the
OfficeAssignment type
modelBuilder.Entity<OfficeAssignment>().HasKey(t => t.InstructorId);
- How to Configure a Composite Primary Key ?
- DepartmentId and Name properties to be the composite primary key of the
Department type
modelBuilder.Entity<Department>()
.HasKey(t => new { t.DepartmentId, t.Name });
- How to Switch off Identity for Numeric Primary Keys ?
- DepartmentId property value will not be generated by the database
modelBuilder.Entity<Department>()
.Property(t => t.DepartmentId)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
- How to Specify the Maximum Length on a Property ?
- Name property should be no longer than 50 characters
- If you make the value longer than 50 characters, you will get a
DbEntityValidationException exception
- If Code First creates a database from this model it will also set the
maximum length of the Name column to 50 characters
modelBuilder.Entity<Department>().Property(t => t.Name).HasMaxLength(50);
Conclusion
- How to Configure the Property to be Required ?
- Name property is required
- If you do not specify the Name, you will get a
DbEntityValidationException exception
- If Code First creates a database from this model then the column used to store
this property will be non-nullable
modelBuilder.Entity<Department>().Property(t => t.Name).IsRequired();
- How to Specify Not to Map a CLR Property to a Column in the Database ?
modelBuilder.Entity<Department>().Ignore(t => t.Budget);
- How to Map a CLR Property to a Specific Column in the Database ?
- Maps the Name CLR property to the DepartmentName database column
modelBuilder.Entity<Department>()
.Property(t => t.Name)
.HasColumnName("DepartmentName");
- How to Rename a Foreign Key That Is Not Defined in the Model ?
- If you choose not to define a foreign key on a CLR type,
- But want to specify what name it should have in the database
modelBuilder.Entity<Course>()
.HasRequired(c => c.Department)
.WithMany(t => t.Courses)
.Map(m => m.MapKey("ChangedDepartmentId"));
- How to Configure whether a String Property Supports Unicode Content ?
- By default strings are Unicode (nvarchar in SQL Server)
- You can use the IsUnicode method to specify that a string should be of varchar type
modelBuilder.Entity<Department>().Property(t => t.Name).IsUnicode(false);
- How to Configure the Data Type of a Database Column ?
- The HasColumnType method enables mapping to different representations
of the same basic type
- Using this method does not enable you to perform any conversion
of the data at run time
of the data at run time
- Note that : IsUnicode is the preferred way of setting columns to varchar,
as it is database agnostic
modelBuilder.Entity<Department>()
.Property(p => p.Name)
.HasColumnType("varchar");
- How to Configure Properties on a Complex Type ?
Way 1 : You can call Property on ComplexTypeConfiguration
modelBuilder.ComplexType<Details>()
.Property(t => t.Location)
.HasMaxLength(20);
Way 2 : You can also use the dot notation to access a property of a complex type
modelBuilder.Entity<OnsiteCourse>()
.Property(t => t.Details.Location)
.HasMaxLength(20);
- How to Configure a Property to Be Used as an Optimistic Concurrency Token ?
Way 1 : You can use either the ConcurrencyCheck attribute
or the IsConcurrencyToken method
modelBuilder.Entity<OfficeAssignment>()
.Property(t => t.Timestamp)
.IsConcurrencyToken();
Way 2 : You can also use the IsRowVersion method
modelBuilder.Entity<OfficeAssignment>()
.Property(t => t.Timestamp)
.IsRowVersion();
- You can use Fluent API with Code First development, when you want to override the default conventions maintained by the Entity Framework
- I will explain Type Mapping and Configuring Relationships with my future Blog Post
- So Try This and Enjoy it
I hope this helps to You.Comments and feedback greatly appreciated.
0 comments:
Post a Comment