将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类。