entity framework code first attributes in combination with fluent api configurations

☆樱花仙子☆ 提交于 2019-12-10 13:46:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!