将LINQ扩展为SQL生成的类

时间:2011-11-25 09:57:22

标签: c# asp.net .net asp.net-mvc linq-to-sql

我选择了LINQ to SQL作为ASP .NET MVC3项目的ORM框架。在我面临需要在注册表单中添加额外字段“确认密码”之前,一切都很好。正如在SO上的一个问题中提到的那样(遗憾的是我目前无法找到它),最好使用接口将生成的LINQ扩展为具有验证属性的SQL类,而不是使用另一个类来存储验证属性。所以我们走了:

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; }
}

视图是具有RegTryViewModel模型的强类型视图。

我只是在这里问我要确保我做的一切都正常。让我感到不舒服的是我在IRegTry接口和RegTryViewModel类之间传播验证逻辑。但我无法将ConfirmPassword属性添加到IRegTry接口,因为基本SQL到LINQ类根本没有它。 先谢谢你们!

2 个答案:

答案 0 :(得分:1)

如果您使用的是View Model类,则不需要连接到DAL Model类的验证逻辑,因此您不需要将该验证接口链接到DAL Model类。

答案 1 :(得分:1)

我知道你已经接受了这个答案,但我认为最好使用partial类来设置它。只要您使用相同名称在同一partial中设置namespace类,就会自动设置所有内容。这是我在我的一个项目中如何设置它的一个例子:

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<ValidationResult> 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方法。您可以在验证方法中检查Confirm==Password

您可以在此Pluralsight Video

中获取更多信息
相关问题