Can I use code first attributes in combination with fluent-API configurations for my entities in Entity Framework?
Thank you.
Data annotations and the fluent API can be used together, but Code First gives precedence to Fluent API > data annotations > default conventions. Fluent API is another way to configure your domain classes.
Everything what you can configure with DataAnnotations is also possible with the Fluent API. The reverse is not true. So, from the viewpoint of configuration options and flexibility the Fluent API is "better".
Configuring a primary key By convention, a property named Id or <type name>Id will be configured as the primary key of an entity. Owned entity types use different rules to define keys. You can configure a single property to be the primary key of an entity as follows: Data Annotations.
Fluent API configures the following aspect of a model in Entity Framework 6: Model-wide Configuration: Configures the default Schema, entities to be excluded in mapping, etc.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With