2013-03-11 51 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; 
} 

目前这段代码不会编译,因为我无法像这样列举我的模型。我想要做的是循环模型中的每个项目,并执行switch语句来构建正确的dbType参数。

任何人都有如何更改此代码的建议吗?

谢谢!

回答

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

希望这有助于。