Configure Domain Classes (configuration Domain class) [EF Code-First series], efcodefirst
In the previous section, we learned the default Code-First Convention. Code-First uses the default convention to generate a conceptual model based on your domain class.
The Code-First mode initiates a programming mode: the Convention is greater than the configuration. This means that when you need it, you can rewrite these conventions by configuring your domain class. There are two ways to configure your domain entity:
Data annotation:
Data annotation is a simple configuration-based feature that you can apply to your domain class or its attributes. You may find that most of the features are in the following command space:
System. componentModel. dataAnnotations, however, data annotation only provides a subset of the Fluent API configuration. Therefore, if you do not find any attribute in the Data annotation, you can use the Fluent API for configuration.
The following example shows a simple example of using data Annotations:
using System;using System.Collections.Generic;using System.ComponentModel.DataAnnotations;using System.ComponentModel.DataAnnotations.Schema;using System.Linq;using System.Text;using System.Threading.Tasks;namespace EF2{ [Table("StudentInfo")] public class Student { [Key] public int SID { get; set; } [Column("Name",TypeName="ntext")] [MaxLength(20)] public string StudentName { get; set; } [NotMapped()] public int? Age { get; set; } public int StdId { get; set; } [ForeignKey("StdId")] public virtual Standard Standard { get; set; } }}
The generated database is like this.
Fluent API
Fluent API configuration, using EF to build a model from your object class, you can inject this configuration, by rewriting the DbContext class "OnModelCreating" method, for example:
Using System; using System. collections. generic; using System. data. entity; using System. linq; using System. text; using System. threading. tasks; namespace EF2 {public class DbContextClass: DbContext {public DbContextClass (): base ("Constr") {} public DbSet <Student> Students {get; set ;} public DbSet <Standard> Standards {get; set;} protected override void OnModelCreating (DbModelBuilder modelBuilder ){
// Configure the domain entity here by using Dluent API Database. SetInitializer (new DropCreateDatabaseIfModelChanges <DbContextClass> (); base. OnModelCreating (modelBuilder );}}}
You can use modelBuilder, which is an object of DbModelBuilder class, to configure domain classes.
You can use modelBuider, an object of the DBModelBuilder class, to configure domain classes.
Let's see DataAnnotation and Fluent API in detail in the next chapter.
We will learn more about data annotation and Fluent API in later sections.