实体框架代码优先属性与流利的api配置结合 [英] entity framework code first attributes in combination with fluent api configurations

查看:75
本文介绍了实体框架代码优先属性与流利的api配置结合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在实体框架中将代码优先属性与fluent-API配置结合使用吗?

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

谢谢。

推荐答案

可以。我通常更喜欢定义一些约束(例如,使用 [Required] 来创建必需的属性,或者使用来定义字符串属性的长度) StringhLength(1,10)):

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;}

,我通常使用流利的api来定义关系(例如一对多关系)

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)

但是,您可能更喜欢使用流畅的API来在模型中实现约束。也就是说,您只能使用流利的API来完成所有操作。但是,数据注释不是那么全面。检查这些以获取更多信息:

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 -流利

这篇关于实体框架代码优先属性与流利的api配置结合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆