EFEF框架 Code First Fluent API

Posted 杨浪

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了EFEF框架 Code First Fluent API相关的知识,希望对你有一定的参考价值。

在Code First方法中,还可以通过Fluent API的方式来处理实体与数据表之间的映射关系。

要使用Fluent API必须在构造自定义的DbContext时,重写OnModelCreating方法,在此方法体内调用Fluent API。

如下面代码所示:

 
  public class BlogDbContext : DbContext
    { 
         public BlogDbContext()
            : base("name=BlogDB2005")
        {
            
        }
         protected override void OnModelCreating(DbModelBuilder modelBuilder)
         {
         
             //do something
             base.OnModelCreating(modelBuilder);
         }
    }
 

下面来看一些简单的例子

主键

modelBuilder.Entity<BlogUser>().HasKey(user => user.UserId);

联合主键

 //联合主键
 modelBuilder.Entity<BlogUser>().HasKey(user => new { user.UserId, user.BlogName });

字段非空

//要求属性必填
modelBuilder.Entity<BlogUser>().Property(user => user.BlogName).IsRequired();

设定字段最大长度

modelBuilder.Entity<BlogUser>().Property(user => user.BlogName).HasMaxLength(20);

设置复杂属性,相当数据特性中的ComplexType

modelBuilder.ComplexType<Address>();

属性字段不映射到数据表字段,相当于数据特性中的NotMapped

 modelBuilder.Entity<BlogUser>().Ignore(user => user.MyProperty);

设置字段是否自动增长  

//设置自动增长,如不需要自动增长,则设为 DatabaseGeneratedOption.None
 modelBuilder.Entity<BlogUser>().Property(user => user.UserId)
              .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

设置外键

 
 ///产生一对多的关系
  modelBuilder.Entity<Post>()
              .HasRequired(p =>p.BlogUser)
             .WithMany(user => user.Posts)
             .HasForeignKey(p => p.UserId);

  ///与上面等效
  //modelBuilder.Entity<BlogUser>()
          //    .HasMany(user => user.Posts)
          //    .WithRequired(p => p.BlogUser)
          //    .HasForeignKey(p => p.UserId);
 

设定实体映射到数据库中的表名

 modelBuilder.Entity<BlogUser>().ToTable("MyUser");

设置实体属性映射到数据库中的列名

 modelBuilder.Entity<BlogUser>()
             .Property(user => user.Description)
             .HasColumnName("userDescription")
             .HasColumnType("ntext");

下面给出完整代码,方便测试

 1  class FluentAPISample
 2     {
 3 
 4         static void Main(string[] args)
 5         {
 6             using (var db = new BlogDbContext())
 7             {
 8                 db.Database.Create();
 9             }
10         }
11     }
12 
13     public class BlogDbContext : DbContext
14     { 
15          public BlogDbContext()
16             : base("name=BlogDB2005")
17         {
18             Database.SetInitializer<BlogDbContext>(
19                 new DropCreateDatabaseIfModelChanges<BlogDbContext>()
20                 );
21         }
22          protected override void OnModelCreating(DbModelBuilder modelBuilder)
23          {
24              modelBuilder.Entity<BlogUser>().HasKey(user => user.UserId);
25              //联合主键
26              //modelBuilder.Entity<BlogUser>().HasKey(user => new { user.UserId, user.BlogName });
27 
28              //设置自动增长,如不需要自动增长,则设为 DatabaseGeneratedOption.None
29              modelBuilder.Entity<BlogUser>().Property(user => user.UserId)
30                  .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
31 
32              //要求属性必填
33              modelBuilder.Entity<BlogUser>().Property(user => user.BlogName).IsRequired();
34              modelBuilder.Entity<BlogUser>().Property(user => user.BlogName).HasMaxLength(20);             
35              modelBuilder.Entity<BlogUser>().Ignore(user => user.MyProperty);
36 
37              modelBuilder.ComplexType<Address>();
38 
39              ///产生一对多的关系
40              modelBuilder.Entity<Post>()
41                  .HasRequired(p =>p.BlogUser)
42              .WithMany(user => user.Posts)
43              .HasForeignKey(p => p.UserId);
44 
45              ///与上面等效
46              //modelBuilder.Entity<BlogUser>()
47              //    .HasMany(user => user.Posts)
48              //    .WithRequired(p => p.BlogUser)
49              //    .HasForeignKey(p => p.UserId);
50 
51              modelBuilder.Entity<BlogUser>().ToTable("MyUser");
52 
53              modelBuilder.Entity<BlogUser>()
54                  .Property(user => user.Description)
55                  .HasColumnName("userDescription")
56                  .HasColumnType("ntext");
57 
58              base.OnModelCreating(modelBuilder);
59          }
60     }
61 
62     public partial class BlogUser
63     {
64         public int UserId { get; set; }
65         public string BlogName { get; set; }
66         public int MyProperty { get; set; }
67         public Address Address { get; set; }
68         public string Description { get; set; }
69         public virtual ICollection<Post> Posts { get; set; }
70     }
71     public partial class Post
72     {
73         public int PostId { get; set; }
74         public string PostTitle { get; set; }
75         public int UserId { get; set; }
76         public BlogUser BlogUser { get; set; }
77     }
78     public partial class Address
79     {
80         public string Province { get; set; }
81         public string City { get; set; }
82     }
 1  class FluentAPISample
 2     {
 3 
 4         static void Main(string[] args)
 5         {
 6             using (var db = new BlogDbContext())
 7             {
 8                 db.Database.Create();
 9             }
10         }
11     }
12 
13     public class BlogDbContext : DbContext
14     { 
15          public BlogDbContext()
16             : base("name=BlogDB2005")
17         {
18             Database.SetInitializer<BlogDbContext>(
19                 new DropCreateDatabaseIfModelChanges<BlogDbContext>()
20                 );
21         }
22          protected override void OnModelCreating(DbModelBuilder modelBuilder)
23          {
24              modelBuilder.Entity<BlogUser>().HasKey(user => user.UserId);
25              //联合主键
26              //modelBuilder.Entity<BlogUser>().HasKey(user => new { user.UserId, user.BlogName });
27 
28              //设置自动增长,如不需要自动增长,则设为 DatabaseGeneratedOption.None
29              modelBuilder.Entity<BlogUser>().Property(user => user.UserId)
30                  .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
31 
32              //要求属性必填
33              modelBuilder.Entity<BlogUser>().Property(user => user.BlogName).IsRequired();
34              modelBuilder.Entity<BlogUser>().Property(user => user.BlogName).HasMaxLength(20);             
35              modelBuilder.Entity<BlogUser>().Ignore(user => user.MyProperty);
36 
37              modelBuilder.ComplexType<Address>();
38 
39              ///产生一对多的关系
40              modelBuilder.Entity<Post>()
41                  .HasRequired(p =>p.BlogUser)
42              .WithMany(user => user.Posts)
43              .HasForeignKey(p => p.UserId);
44 
45              ///与上面等效
46              //modelBuilder.Entity<BlogUser>()
47              //    .HasMany(user => user.Posts)
48              //    .WithRequired(p => p.BlogUser)
49              //    .HasForeignKey(p => p.UserId);
50 
51              modelBuilder.Entity<BlogUser>().ToTable("MyUser");
52 
53              modelBuilder.Entity<BlogUser>()
54                  .Property(user => user.Description)
55                  .HasColumnName("userDescription")
56                  .HasColumnType("ntext");
57 
58              base.OnModelCreating(modelBuilder);
59          }
60     }
61 
62     public partial class BlogUser
63     {
64         public int UserId { get; set; }
65         public string BlogName { get; set; }
66         public int MyProperty { get; set; }
67         public Address Address { get; set; }
68         public string Description { get; set; }
69         public virtual ICollection<Post> Posts { get; set; }
70     }
71     public partial class Post
72     {
73         public int PostId { get; set; }
74         public string PostTitle { get; set; }
75         public int UserId { get; set; }
76         public BlogUser BlogUser { get; set; }
77     }
78     public partial class Address
79     {
80         public string Province { get; set; }
81         public string City { get; set; }
82     }

 

运行结果如下图示:

以上是关于EFEF框架 Code First Fluent API的主要内容,如果未能解决你的问题,请参考以下文章

EFEF Code First Migrations数据库迁移

如何使用 Entity Framework Code First Fluent API 指定表名

Entity Framework Code-First(10):Fluent API

Code First约定-Fluent API配置

Code First Fluent API,我该怎么做?

Code First约定-Fluent API配置