使用实体框架的Code First属性结合Fluent API配置

5

我可以在Entity Framework中将Code First属性与Fluent API配置结合使用吗?

谢谢。


如果可能的话,最好避免这样做,因为您的实体元数据/映射将分散在两个文件中,有时可能会导致错误或重复工作。 - Ognyan Dimitrov
1个回答

5

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

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

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

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

然而,您也可以选择使用流畅的API来实现模型中的约束。也就是说,您可以仅使用流畅的API来完成所有操作。但是,数据注释不是那么全面。请查阅这些内容以获取更多信息:

https://dev59.com/Em435IYBdhLWcg3wigux#5356222

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

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


非常感谢您,erkaner。 - Zole

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接