6 Configure Domain Classes in Code
6 Configure Domain Classes in Code
Code-First:
We learned default Code-First Conventions in the previous section. Code-First
builds conceptual model from your domain classes using default conventions.
Code-First leverages a programming pattern referred to as convention over
configuration. It means you can override these conventions by configuring your
domain classes to provide EF with the information it needs. There are two ways
to configure your domain classes.
1. DataAnnotations
2. Fluent API
DataAnnotation:
DataAnnotation is a simple attribute based configuration, which you can apply
to your domain classes and its properties. You can find most of the attributes in
the System.ComponentModel.DataAnnotations namespace. However,
DataAnnotation provides only a 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.
[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; }
[ForeignKey("StdId")]
public virtual Standard Standard { get; set; }
}
Fluent API:
Fluent API configuration is applied as EF builds the model from your domain
classes You can inject the configurations by overriding the DbContext
class' OnModelCreating method as following:
Let's see DataAnnotation and Fluent API in detail in the next chapter.