我可以在Entity Framework中将Code First属性与Fluent API配置结合使用吗?
谢谢。
我可以在Entity Framework中将Code First属性与Fluent API配置结合使用吗?
谢谢。
是的,你可以这样做。我通常更喜欢定义一些约束条件(例如,使用[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