0

我有一个 MVC3 应用程序,我想将我的模型传递给一个构建命令对象的方法。原因是我有很多带有命令对象的方法,我希望代码写得更好。

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 参数。

有人对如何更改此代码有建议吗?

谢谢!!

4

1 回答 1

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

希望这可以帮助。

于 2013-03-11T19:57:21.117 回答