5

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

Thank you.

Zole
  • 69
  • 5
  • You can, but you better avoid it if possible because your entities metadata/mappings will be spread between two files which may cause mistakes or double work sometimes. – Ognyan Dimitrov Apr 17 '15 at 06:45

1 Answers1

5

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

Community
  • 1
  • 1
renakre
  • 8,001
  • 5
  • 46
  • 99