2013-03-11 2 views
0

MVC3 응용 프로그램이 있고 명령 개체를 작성하는 메서드에 내 모델을 전달하고 싶습니다. 그 이유는 내가 명령 객체를 가진 많은 메소드를 가지고 있고 코드를 더 잘 작성하기를 원하기 때문입니다.루프 스루 모델 및 빌드 SqlCommand obj

private static SqlCommand CommandObj(vw_UserManager_Model model) 
{ 
    SqlCommand command = new SqlCommand(); 
    command.CommandType = CommandType.StoredProcedure; 


    foreach (var item in model) 
    { 
     switch (property.PropertyType.Name) 
     { 
      case "String": 
       command.Parameters.Add("@" + property.Name, SqlDbType.VarChar).SqlValue = property; 
       break; 
      case "Guid": 
       command.Parameters.Add("@" + property.Name, SqlDbType.UniqueIdentifier).SqlValue = property; 
       break; 
      case "Int32": 
       command.Parameters.Add("@" + property.Name, SqlDbType.Int).SqlValue = property; 
       break; 
      case "Boolean": 
       //switch (property.Name.FirstOrDefault()) 
       //{ 
       // case true: 
       //  command.Parameters.Add("@isactive", SqlDbType.Bit).SqlValue = 1; 
       //  command.Parameters.Add("@isapproved", SqlDbType.Bit).SqlValue = 1; 
       //  break; 
       // case false: 
       //  command.Parameters.Add("@isactive", SqlDbType.Bit).SqlValue = 0; 
       //  command.Parameters.Add("@isapproved", SqlDbType.Bit).SqlValue = 0; 
       //  break; 
       //} 
       break; 
     } 
    } 

    return command; 
} 

현재이 모델을 통해 열거 할 수 없기 때문에이 코드는 컴파일되지 않습니다. 내가하고 싶은 작업은 모델의 각 항목을 반복하고 올바른 dbType 매개 변수를 작성하기 위해 switch 문을 수행하는 것입니다.

누구나이 코드를 변경하는 방법에 대한 제안이 있습니까?

감사합니다.

답변

0

잘하면 귀하의 질문을 이해했습니다. 이런 식으로하려고하는 것처럼 보입니다. 여기 내 모델 클래스는 다음과 같습니다

public class Person 
{ 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    public int Age { get; set; } 
    public bool Married { get; set; } 
} 

여기에 모델 속성을 통해 루프 코드입니다 :이 도움이

public static void Main(string[] args) 
{ 
    Person person = new Person(); 
    var modelProperties = person.GetType().GetProperties(); 

    foreach (var property in modelProperties) 
    { 
     switch (property.PropertyType.Name) 
     { 
      case "String": 
       Console.WriteLine("Property {0} is a string", property.Name); 
       break; 
      case "Int32": 
       Console.WriteLine("Property {0} is an int", property.Name); 
       break; 
      case "Boolean": 
       Console.WriteLine("Property {0} is a boolean", property.Name); 
       break; 
      default: 
       Console.WriteLine("Type unknown!"); 
       break; 
     } 
    } 

희망.