annotations 和 fluent api的选择

1.什么是annotations 和 fluent api?

  两者都是用来对mvc中的model进行限定的,比如规定某个字符串属性要【 非空,最长为50个字符】。annotations和fluent api 是两种风格的写法。

(a) annotations风格是指 直接在model 这个类 把限制标注在属性的上面:

[Required,MaxLength(50)]
public string  Name{get;set;}

(b) fluent api 风格 是用单独的代码 写出 属性的 限定条件。

modelBuilder.Entity<Customer>().Property(p => p.Name).HasMaxLength(50);

2.什么时候用annotations,什么时候用fluent api 呢?

  二者在效果上其实是等效的。微小的区别比如: annotations 可以限定属性 的最小长度MinLength,而fluent api没有这个。

  使用annotations的好处是所有和model有关的东西都放在 当前这个model类,易于查找。

  使用fluent api的好处是能保持代码的整洁。特别是 使用EF的Code First 已有数据库模式。(这是Code First的一个常用模式。这个模式是对于已经存在的数据库,我们写好model,通过EF使之映射。)这个模式可以用的工具有Power Tool(这个工具可以绑定数据库之后,生成MVC中的model)。这时候再用fluent api 去修改这个model,使用起来挺方面的。

  代码1-1:


[Table("CompanyInfo")] public class CompanyInfo { [Key] [Display(Name = "流水号")] public int id { get; set; } [Display(Name = "单位名称")] [Required(AllowEmptyStrings = false, ErrorMessage = "请输入单位名称")] [Column("CompanyName")] public string CompanyName { get; set; } [Display(Name = "省份")] [Column("ProvinceId")] [Required(AllowEmptyStrings = false, ErrorMessage = "请选择省份")] public string ProvinceId { get; set; } [Display(Name = "城市")] [Column("CityId")] [Required(AllowEmptyStrings = false, ErrorMessage = "请选择城市")] public string CityId { get; set; } }

 

  上面的代码是annotations 风格的,所有的东西都放在model类里面。

  改成fluent api风格的。

    public class CompanyInfo {
        public int id { get; set; }
        public string CompanyName { get; set; }
        public string ProvinceId { get; set; }
        public string CityId { get; set; }
    }

  这个类很直接明了。那我们把那些 属性上面的限制,还有映射到数据库的哪张表放在哪呢?答案是 单独写个mapping类。  我们可以在项目中建个文件Mapping ,里面放着每个model和数据库映射的mapping类。mapping类如下:

 public class CompanyInfoMap : EntityTypeConfiguration<CompanyInfo> {
        public CompanyInfoMap() {
            this.ToTable("CompanyInfo");//model对应于数据库的companyInfo表
            this.HasKey(t=>t.id);//id这个属性是 主键
            //还有一些属性的设置
        }

  要使这个fluent api 产生限定,我们还需要最后一步: 把这个CompanyInfoMap类 添加到DataContext的重写方法OnModelCreating中。

protected override void OnModelCreating(DbModelBuilder modelBuilder){
    modelBuilder.Configurations.Add(new CompanyInfoMap());
}

   OK!使用fluent api的方法就完成了。

3.特殊情况

  使用fluent api确实带来很多方便。但是有些不得不在model用annotations风格。比如上面代码1-1中的 

    [Display(Name = "城市")]
    [Column("CityId")]
    Required(AllowEmptyStrings = false, ErrorMessage = "请选择城市")]

  Display标识和Required中的ErrorMessage 这些属于与Mvc的View 打交道的限定条件或者验证,一般都是直接标注在model类的属性上面啦!

fluent api 更多关注的是一种把数据库中的表比如nvarchar(50),非空等这些东西,与我们对应model的关系。而UI验证等方面就交给annotaitons 这种方式吧。

  以上是我的个人理解,欢迎路过的各位大神指正!

 

 

posted @ 2014-02-23 23:11  本杰明·喝茶  阅读(1191)  评论(0编辑  收藏  举报