i am getting an error on DuplicateOrder(TestOrder) as "cannot convert from tables.Order to int" even though the OrderID in the Orders table is an int
void DuplicateOrder(int orderId)
{
string methodName = MethodBase.GetCurrentMethod().Name;
try {
using (MSBLegacyContext db = new MSBLegacyContext())
{
var TestOrder = db.Orders.Where(i=>i.OrderID == orderId).FirstOrDefault();
DuplicateOrder(TestOrder);
}
}
catch (Exception ex)
{
Console.WriteLine(methodName, ex, string.Format("Test", orderId));
}}
what am i missing here?
Root cause, the FirstOrDefault
in below line will return the either first order
object or null.
var TestOrder = db.Orders.Where(i=>i.OrderID == orderId).FirstOrDefault();
So type of testOrder
is order
, but the below method call is expecting the int
parameter.
DuplicateOrder(TestOrder);
That's the reason yor are getting -
cannot convert from tables.Order to int
To fix the issue, you need to add Select query in the Linq query and select the int
column, something like below -
var TestOrder = db.Orders.Where(i=>i.OrderID == orderId).Select(s=> s.YourIntColumn).FirstOrDefault();
Edit:
After looking at you entire method and comments from others, you method call will definitely go to infinite loop. As you have not mentioned the purpose of this code, I am just assuming that you want to see whether a particular orderid
is duplicate in the database or not. For that you can just use Count
query and return the Boolean
value. (not sure why do you have void
in your method signature)
bool DuplicateOrder(int orderId) // changed from void to bool
{
using (MSBLegacyContext db = new MSBLegacyContext())
{
return db.Orders.Where(i=>i.OrderID == orderId).Count()>1; // returns true if more than 1 order found
}
}