将LINQ扩展为SQL生成的类
我已经选择LINQ to SQL作为ASP .NET MVC3项目的ORM框架。 在我面临需要在注册表单中添加额外字段“确认密码”之前,一切都很好。 正如在SO上的一个问题中提到的那样(遗憾的是我目前无法找到它),最好使用接口将生成的LINQ扩展为具有validation属性的SQL类,而不是使用另一个类来存储validation属性。 所以我们走了:
public interface IRegTry { [Required] [Email] string EMail { get; set; } [Required] [StringLength(100, ErrorMessage = "Should not exceed 100 symbols")] string FirstName { get; set; } [Required] string Password { get; set; } } [MetadataType(typeof(IRegTry))] public partial class RegTry : IRegTry { }
RegTry
类是基于数据库实体由LINQ to SQL生成的类。
在View上我们确认了密码字段,这应该确保两个键入的密码彼此相等。
所以在这里我们添加它:
public class RegTryViewModel : RegTry { [Required] [EqualTo("Password", ErrorMessage = "You should type two identical passwords to continue")] public string ConfirmPassword { get; set; } }
View是使用RegTryViewModel
模型的强类型视图。
我只是在这里问我要确保我做的一切都正常。 让我感到不舒服的是我在IRegTry
接口和RegTryViewModel
类之间传播validation逻辑。 但我不能将ConfirmPassword
属性添加到IRegTry
接口,因为基本SQL到LINQ类根本没有它。 先谢谢你们!
我知道你已经接受了这个问题的答案,但我认为使用partial
类来设置它可能会更好。 只要在同一namespace
使用相同名称设置partial
类,就会自动设置所有内容。 以下是我在其中一个项目中进行设置的示例:
namespace OperationsMetrics { [MetadataType(typeof(ClientStatMD))] public partial class client_wkly_stat : IValidatableObject { public class ClientStatMD { [Required(ErrorMessage = "Client selection is required")] public virtual int client_id { get; set; } [Required(ErrorMessage = "SLAs met is required")] public virtual int wkly_sla_met { get; set; } [Required(ErrorMessage = "Total SLAs possible is required")] public virtual int wkly_sla_req { get; set; } [Required(ErrorMessage = "Number of input files is received")] public virtual int num_inp_files_rec { get; set; } [Required] public string client_name { get; set; } } public IEnumerable Validate(ValidationContext validationContext) { if (wkly_sla_met > wkly_sla_req) { yield return new ValidationResult("SLAs met cannot be greater that SLAs possible"); } } public string client_name { get; set; } //this isn't a part of the actual db object but can still be accessed in the Validate method }
}
您可以将Partial Class设置为IValidatableObject
,它实现自己的Validate
方法。 您可以在validation方法中检查Confirm==Password
。
您可以在此Pluralsightvideo中获取更多信息
如果您使用的是View Model类,则不需要连接到DAL Model类的validation逻辑,因此您不需要将该validation接口链接到DAL Model类。
上述就是C#学习教程:将LINQ扩展为SQL生成的类分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/949902.html