entity framework 代码优先属性结合流畅的 api 配置

entity framework code first attributes in combination with fluent api configurations

我可以在 Entity Framework 中将代码优先属性与 fluent-API 配置结合使用吗?

谢谢。

是的,你可以。我通常更喜欢定义一些约束(例如,使用 [Required] 使 属性 成为必需,或者使用 StringhLength(1, 10) 为字符串 属性 定义长度:

  [Required]
  [StringLentgh(1,10)]
  public string BookName {get;set;}

另一方面,我通常使用流利的api来定义关系(例如一对多关系)

  dbContext.Entity<Book>()
           .HasRequired(b => b.Author)
           .WithMany(a => a.Books)
           .HasForeignKey(b => b.AuthorId)

但是,您可能更喜欢使用 fluent API 以及在模型中实施约束。也就是说,你可以只使用流利的API来做所有事情。但是,数据注释并不全面。检查这些以获取更多信息:

http://www.codeproject.com/Articles/476966/FluentplusAPIplusvsplusDataplusAnnotations-plusWor

http://www.codeproject.com/Articles/368164/EF-Data-Annotations-and-Code-Fluent