问题
Can I use code first attributes in combination with fluent-API configurations for my entities in Entity Framework?
Thank you.
回答1:
Yes you can. I generally prefer to define some constraints (for example, making a property required by using [Required]
or to define a length for a string property by using StringhLength(1, 10)
):
[Required]
[StringLentgh(1,10)]
public string BookName {get;set;}
On the other hand, I generally use fluent api to define the relationships (for example, 1-to-many relationship)
dbContext.Entity<Book>()
.HasRequired(b => b.Author)
.WithMany(a => a.Books)
.HasForeignKey(b => b.AuthorId)
However, you may prefer to use fluent API as well for implementing constraints in your model. That is, you can use only fluent API to do everything. However, data annotations are not that comprehensive. Check these for more information:
https://stackoverflow.com/a/5356222/1845408
http://www.codeproject.com/Articles/476966/FluentplusAPIplusvsplusDataplusAnnotations-plusWor
http://www.codeproject.com/Articles/368164/EF-Data-Annotations-and-Code-Fluent
来源:https://stackoverflow.com/questions/29668136/entity-framework-code-first-attributes-in-combination-with-fluent-api-configurat