2010-01-11 5 views
2

사용자 정의 데이터 주석이 작동하는 데 문제가 있습니다. 고객 (CustomerID)의 UsergroupName이 고유하다는 유효성 검증 속성을 추가하려고합니다.데이터 주석을 사용한 사용자 정의 유효성 검사

[MetadataType(typeof(UsergroupMetaData))] 
public partial class Usergroup { } 

public class UsergroupMetaData 
{ 
    [Required()] 
    public object CustomerID { get; set; } 

    [Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "UsergroupNameRequired")] 
    public object UsergroupName { get; set; } 

    [UniqueUsergroupName(????)] 
    // what to put here? 
} 



public class UniqueUsergroupName : ValidationAttribute 
{ 
    UsergroupRepository _rep = new UsergroupRepository(); 

    public override bool IsValid(object value, int customerID) 
    { 
     var x = _rep.GetUsergroups().ByUsergroupName(value).ByCustomerID(customerID); 

     // what to put here? 

     return false; 
    } 
} 

"개수> 0"이면 IsValid가 false를 반환해야합니다.

어떻게 수정하여 작동합니까? GetUsergroups()는 IQueryable을 반환합니다.

편집 : 매개 변수로 현재의 CustomerID를 전달할 수있는 방법

[MetadataType(typeof(UsergroupMetaData))] 
public partial class Usergroup { } 

public class UsergroupMetaData 
{ 
    public object CustomerID { get; set; } 

    [Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "UsergroupNameRequired")] 
    [UniqueUsergroupName(ErrorMessageResourceType= typeof(Resources), ErrorMessageResourceName = "UsergroupNameExists")] 
    public object UsergroupName { get; set; } 


} 


public class UniqueUsergroupName : ValidationAttribute 
{ 

    UsergroupRepository _rep = new UsergroupRepository(); 

    public override bool IsValid(object value, int customerID) 
    { 

     int usergroups = _rep.GetUsergroups().ByCustomerID(customerID).ByUsergroupName(value.ToString()).Count(); 

     return usergroups >0; 
    } 
} 

? 같은 UsergroupName있는 모든 "기타"UsergroupMetaData 를 확인할 수 있도록

/M은

답변

2

당신은 검색에서 ID 속성을 포함하려면이 방법
http://byatool.com/mvc/custom-data-annotations-with-mvc-how-to-check-multiple-properties-at-one-time/
을 적용 할 수 있습니다.

시나리오에 적용하는 데 문제가 있으면 확인하고 전화 해주세요.

편집 : 더 설명

나의 이해는 같은 UsergroupName 다른 UsergroupMetaData 개체가 있는지 여부를 확인해야한다는 것입니다.

의 우리가 발리는 전체 클래스에없는 속성을하게 만들거야 가정 해 봅시다 :

[UniqueUsergroupName] 
public class UsergroupMetaData 

어떤 매개 변수가 필요하지 않습니다. UniqueUsergroupName Validate() 메소드가 어떻게 보이는지 보자 :

public override Boolean IsValid(Object value) 
{ 
    var usergroupName = value != null ? value.ToString() : null; 
    //We don't validate empty fields, the Required validator does that 
    if(string.IsNullOrEmpty(usergroupName)) return true; 

    Type objectType = value.GetType(); 
    //Get the property info for the object passed in. This is the class the attribute is 
    // attached to 
    //I would suggest caching this part... at least the PropertyInfo[] 
    PropertyInfo[] neededProperties = 
    objectType.GetProperties(); 

    var customerIdProperty = neededProperties 
    .Where(propertyInfo => propertyInfo.Name == "CustomerID") 
    .First(); 
    var customerId = (int?) customerIdProperty.GetValue(value, null); 

    var usergroupNameProperty = neededProperties 
    .Where(propertyInfo => propertyInfo.Name == "UsergroupName") 
    .First(); 
    var usergroupName = (string) customerIdProperty.GetValue(value, null); 

    // Now I don't userstand why the blog post author did all this reflection stuff to 
    // get the values of the properties. I don't know why he just didn't d something like: 
    // var usergroup = (Usergroup) value; 
    // var customerId = usergroup.CustomerId; 
    // var usergroupName = usergroup.UsergroupName; 
    // 
    //I think reflection was not needed here. Try both ways anyway. 
    // The next lines should not be different regardless of whether you used reflection. 
    // 

    //We don't validate empty fields, the Required validator does that 
    if(string.IsNullOrEmpty(usergroupName)) return true; 

    //Now you have the customerId and usergroupName. Use them to validate. 
    //If I'm using LINQ (for explanation only) it'd be something like: 
    // Assuming _rep.GetUsergroups() returns IQueryable (only for explanation): 
    int numberOfOtherUsergroupsWithSameName = 
     _rep.GetUsergroups() 
       .Where(g => g.UsergroupName == usergroupName && g.CustomerId != customerId) 
       .Count(); 
    return numberOfOtherUsergroupsWithSameName == 0; 
} 
+0

필자의 시나리오에서는 어떻게 적용해야하는지 알 수 없다. 그것은 데이터베이스와 모두를 사용하기 때문입니다. 특히 CustomerID가 nullable이고 필수는 아닌 경우. –

+0

필자는이 아이디어가 귀하의 상황에서 어떻게 사용될 수 있을지 설명하기 위해 필기 코드를 추가했습니다. 그것을 확인하고 그게 당신을 위해 작동하는지 말해봐. 게시물에서 볼 수 있듯이 주요 속성은 특정 속성뿐만 아니라 전체 클래스에 대해 유효성 검사 속성이 작동한다는 것입니다. 어떻게되는지 말해줘. – Meligy

관련 문제