Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

entity framework code first attributes in combination with fluent api configurations

Can I use code first attributes in combination with fluent-API configurations for my entities in Entity Framework?

Thank you.

like image 646
Zole Avatar asked Apr 16 '15 07:04

Zole


People also ask

Does data annotation attributes override Fluent API configuration?

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.

Why might you choose the Fluent API in preference to annotation attributes?

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".

How do you configure a primary key for an entity in Entity Framework Fluent API?

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.

Which of the following configuration activities Fluent API does?

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.


1 Answers

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

like image 119
renakre Avatar answered Sep 17 '22 12:09

renakre