我可以用Fluent Api替换一些吗? [英] Can I replace some of this with the Fluent Api?
问题描述
[必需]
[StringLength(100,ErrorMessage ={0}必须至少为{2}个字符长,MinimumLength = 6)]
[DataType(DataType.Password)]
[显示(Name =Password)]
public string Password {get;组;
我不想用这些注释来装饰我的密码属性。如果可能,我宁愿使用Fluent Api。使用Fluent Api可以完成多少注释?我知道必需可以和StringLength。但我不知道ErrorMessage,DataType和Display。
我知道必需可以和StringLength。
这就是全部。
请记住,不同的框架可以使用相同的属性,非常不同的目的如果您在ASP.NET MVC的上下文中使用 - 例如必需
属性,则将用于MVC模型验证 - 在客户端通过注入页面的某些Javascript或在服务器端设置 ModelState.IsValid
。
必需
属性也被Entity Framework Code-First用于验证一个实体,但这实际上与MVC模型验证无关。如果您使用Fluent API将配置替换为 Required
属性,那么您仍然会影响Entity Framework,但是对于ASP.NET MVC,您只需删除该属性,即不再需要该属性用于MVC验证。 ASP.NET MVC不关心Entity Framework的Fluent API。
对于 StringLength
也是如此。 ErrorMessage
, DataType
和显示
与实体框架无关,既不属于Fluent API的属性也没有对应。
Say I have the following property in a class (where I'm using Code First):
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
I'd rather not decorate my Password property with these annotations. I'd rather use the Fluent Api if possible. How many of these annotations could be done using the Fluent Api? I know Required can be, and StringLength. But I don't know about ErrorMessage, DataType and Display.
I know Required can be, and StringLength.
And that's all.
Keep in mind that the same attributes can be used by different "frameworks" and for very different purposes. If you use - for example - the Required
attribute in a context of ASP.NET MVC it will be used for MVC model validation - on client side by some Javascript injected into the page or on server side to set ModelState.IsValid
.
The Required
attribute is also used by Entity Framework Code-First to validate an entity, but this has actually nothing to do with the MVC model validation. If you replace the Required
attribute by configuration with Fluent API you still influence Entity Framework, but for ASP.NET MVC you just have removed the attribute, i.e. the property is not required anymore for MVC validation. ASP.NET MVC doesn't care about Entity Framework's Fluent API.
The same is true for StringLength
. ErrorMessage
, DataType
and Display
play no role with Entity Framework, neither as attributes nor are there counterparts in Fluent API.
这篇关于我可以用Fluent Api替换一些吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!