Entity Framework Code-First(8):Configure Domain Classes
2016-07-05 16:22
288 查看
Configure Domain Classes in 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.DataAnnotations
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 theSystem.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.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 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: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.
相关文章推荐
- HDU 2389 Rain on your Parade (二分匹配)
- Ruby on Rails框架程序连接MongoDB的教程
- POJ 3714 Raid
- login SMTP send mail error : Unable to read data from the transport connection: net_io_connectionclosed
- linux进程(fork,waitpid)
- Could not generate DH keypair
- 缓存相关(一)-InputStream、AIDL
- http://blog.csdn.net/u013256816/article/details/51161548
- Helpers\RainCaptcha
- Installation error: INSTALL_FAILED_UPDATE_INCOMPATIBLE
- Waiting because the touched window has not finished
- Opencv研读笔记:haartraining程序之icvCreateCARTStageClassifier函数详解(强分类器创建)
- Mailing API
- awk 中 对于tail f 的文件重定向
- Baidu URL的部分参数
- linphone之linphonec_main_loop分析
- 解决Failed to execute goal org.apache.maven.plugins
- Fail2ban初识
- linker command failed with exit code 1 (use -v to see invocation)
- 人工智能 人们的智能