EF5代码优先-数据注释与Fluent API [英] EF5 Code First - Data Annotations vs Fluent API

查看:88
本文介绍了EF5代码优先-数据注释与Fluent API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Entity Framework的新手,并且准备使用EF5 Code First进行新的ASP.NET MVC项目。

I am new to Entity Framework and am about to embark on a new ASP.NET MVC project using EF5 Code First.

据我所知,您可以对域模型对象中的属性使用数据注释,或者可以使用Fluent API定义属性数据类型(创建对象时在数据库中),大小,它们是否可为空等等。

As I understand it, you can either use Data Annotations against the properties within your Domain Model objects, or you can use a Fluent API, to define the properties data type (in the DB when the objects are created), size, whether they are nullable and so on.

是否有一般推荐的方法?

Is there a general recommended approach as to which to go with?

我看不到使用数据注释时的方式,我可以在数据库中创建该属性时为其指定数据类型和大小,而使用Fluent API,看起来可以执行以下操作:

I couldn't see how when using Data Annotations, I can specify the datatype and size for that property when it's created in the DB, whereas with the Fluent API it looks like you can do the following:

Property(g => g.ModelName).HasColumnType("varchar");
Property(g => g.ModelName).HasMaxLength(100);
Property(g => g.ModelName).IsRequired();

使用数据注释时,默认情况下,我所有的字符串属性似乎都使用nvarchar(MAX)例如,

When using Data Annotations, by default it appears to be using nvarchar(MAX) for all my string properties for example.

是否可以使用数据注释来完成上述操作?它是否提供与Fluent API相同程度的调整,还是我应该单独保留域模型,并将所有这些调整分开以为每个域模型对象分离Fluent API类?

Is there a way to do the above using Data Annotations? Does it offer the same degree of 'tweaking' as Fluent API or should I be leaving the domain model alone and separate all of this 'tweaking' to separate Fluent API classes for each domain model object?

推荐答案

我建议使用流畅的API。数据注释是一个子集,例如不包括级联删除关系。

I would recommend the fluent API. Data annotations are a subset, and don't for example include cascading delete for relationships.

此外,您可能会考虑使用诸如数据库列名称之类的持久性逻辑来污染模型

Also, you may consider polluting your models with persistence logic such as database column names inappropriate.

这篇关于EF5代码优先-数据注释与Fluent API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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