将字段标记为必填
如果我有一个 dbml 文件,其中包含一个 Customer 类,其中包含一个 CompanyName 属性;
public partial class Customer : INotifyPropertyChanging, INotifyPropertyChanged
private string _CompanyName;
public string CompanyName
{
get
现在,考虑到上面的内容是在 dbml 中并因此生成的,我显然应该避免像瘟疫一样编辑它。
所以我创建了另一个像这样的类;
public partial class Customer
{
[Required]
public string CompanyName{get;set;}
}
这样做的原因是因为我想根据需要装饰我的字段。
但是,这不起作用,因为我收到编译错误“...已经包含“CustomerID”的定义”。
有谁知道解决这个问题的方法,或者是否有更好的方法来根据需要标记字段或验证模型?
If I have a dbml file that contains say a Customer class with say a single property of CompanyName;
public partial class Customer : INotifyPropertyChanging, INotifyPropertyChanged
private string _CompanyName;
public string CompanyName
{
get
Now, given that the above is in a dbml and thus generated I obviously should avoid editing it like the plague.
So I have created another class like so;
public partial class Customer
{
[Required]
public string CompanyName{get;set;}
}
The reason for this is because I want to decorate my field as being required.
However this doesn't work as I get the compile error "...already contains a definition for 'CustomerID'".
Does anyone know a way around this or is there a better way to mark fields as required or of validating a model?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
解决方案是使用 MetadataType 属性带有包含数据验证注释的附加类。
请参阅: http: //weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx
The solution is to use a MetadataType attribute with an additional class that contains the data validation annotations.
See: http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx
或者您可以使用 ViewModel 模式。当您想要使用下拉列表之类的东西时,这还为您提供了将模型绑定到视图的灵活性。我们将它与 AutoMapper 一起使用。
Or you could use ViewModel pattern. This also gives you flexibility is binding your model to the view when you want to use things like dropdowns. We use it with AutoMapper.