5

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

Thank you.

1
  • 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. Commented Apr 17, 2015 at 6:45

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.