0

My application is in Asp.Net coded in C# and i'm using LINQ for database transactions. My requirement is to get the Max value of the records saved in a certain table, for this i'm using Max() method.

Below is my controller code :

    [HttpPost]
    public ActionResult Create(Entity_Name Entity_Object)
    {
          if (Entity_Object.Condition == true)
          {
                    My required code
          }
          else
          {
                var get_Max_Number = db.Entity_Name.ToList();
                long Max_Number = 0;

                if (get_Max_Number.Count() > 0)
                {
                    Max_Number = Convert.ToInt64(get_Max_Number.Max());

                }
                    My required code
           }
    }

My issue is when i remove the If-else condition then the same Max() method query works perfect, but when i add the If-else statement then i gets the following error.

Error:

At least one object must implement IComparable.

What i tried :

  1. I attempted to remove the If-Else
  2. I placed the Max() method logic above the If-else

Placing the Max() method above If-Else

[HttpPost]
public ActionResult Create(Entity_Name Entity_Object)
{
      var get_Max_Number = db.Entity_Name.ToList();
      long Max_Number = 0;

      if (get_Max_Number.Count() > 0)
      {
             Max_Number = Convert.ToInt64(get_Max_Number.Max());
      }
      if (Entity_Object.Condition == true)
      {
             My required code
      }
      else
      {
             My required code
      }
}
4

1 に答える 1

1

Max()あなたが最大限に得ているものを知る必要があります。クラスに多数のプロパティ (文字列、整数など) が含まれている場合はEntity_Name、何に基づいて最大値を取得するかを指定する必要があります。

もう 1 つのことは、物事の外観から Linq を介して DB に接続しているが、データベース テーブルの内容全体を取得した後、Count() & Max() 関数をメモリ内で実行していることです。テーブルのサイズが大きくなると、これは非常に非効率的になります。LinqToSql と LinqToEF は、これらの関数をデータベース レベルにプッシュすることをサポートしています。コードを次のように変更することをお勧めします。

[HttpPost]
public ActionResult Create(Entity_Name Entity_Object)
{
      if (Entity_Object.Condition == true)
      {
          //My required code
      }
      else
      {
            long Max_Number = 0;
            if(db.Entity_Name.Count() > 0)
            {
                Max_Number = Convert.ToInt64(
                                db.Entity_Name.Max(x => x.PropertyToGetMaxOf)
                             );
            }
            //My required code
       }
}
于 2013-09-18T10:51:12.387 に答える