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 に答える