As you know that you can create entity data model from existing database in database first approach that has all the metadata information in SSDL, CSDL and MSL so that EF can use this model in querying, change tracking, updating functionality etc.. The same way, entity framework code first allows you to use your domain classes to build the model which in-tern will be used by EF in different activity. Code first suggests certain conventions to follow by your domain classes so that EF can understand it and build the model out of it.
However, if your domain classes don’t follow conventions then you also have the ability to configure your domain classes so that EF can understand it and build the model out of it. There are two ways by which you can configure your domain classes:
- DataAnnotation
- Fluent API
DataAnnotation is simple attribute based configuration which you can apply on your domain classes and its properties. You can find most of the attributes in System.ComponentModel.DataAnnotations namespace. However, DataAnnotation provides only subset of Fluent API configurations. So if you don’t find some attributes in DataAnnotation then you have to use Fluent API to configure it.
Following is an example of DataAnnotation used in Student Class:
[Table("StudentInfo")] public class Student { public 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; } }
Fluent API:
Fluent API configuration applied as EF building the model from your domain classes. You can inject the configurations by overriding the DbContext class’s OnModelCreating method as following:
public class SchoolDBContext: DbContext { public SchoolDBContext(): base("SchoolDBConnectionString") { } public DbSet<Student> Students { get; set; } public DbSet<Standard> Standards { get; set; } public DbSet<StudentAddress> StudentAddress { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { //Configure domain classes using Fluent API here base.OnModelCreating(modelBuilder); } }
You can use modelBuilder which is an object of DbModelBuilder class to configure domain classes.
Let’s see DataAnnotation and Fluent API in detail in the next chapter.
No comments:
Post a Comment