0
select * from Employees where DataofJoin ='2005-01-01 00:00:00.000'

I wrote this Linq Query as

public JsonResult Dif() 
{
    var ss = Convert.ToDateTime("2001-01-01 00:00:00.000");
    var x = (from n in db.Employees
                where n.DataofBirth == ss
                select n).First();

    return new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}

But its throwing the following error:

"An exception of type 'System.InvalidOperationException' occurred in System.Core.dll 
but was not handled in user code"
4
  • 2
    Please show us your stacktrace Commented Oct 21, 2016 at 7:01
  • What is StackTrce Commented Oct 21, 2016 at 7:04
  • Title of the question is completely misleading, nothing to do with Sql Datetime query conversion Commented Oct 21, 2016 at 7:42
  • I don't get what your code should do. You instanciate a DataTime object, make a linq quer, store the result in x and return a new JsonResult. But you never assigne the value of x to anything. Commented Oct 21, 2016 at 8:09

1 Answer 1

2

As I can Understand , This issue is because of attempt to get an item from empty object.

Because you are making a call of .First() and there is an empty result returned by the query. So if you do obj.First() of an empty object it throws exception. Use obj.FirstOrDefault() To avoid the exception.

And if Linq is not returning the data is an issue then use Sql Profiler to check what query is been called,or change the date filter accordingly.

To avoid error Use -

    var x = (from n in db.Employees
             where n.DataofBirth == ss
             select n).FirstOrDefault();

Update

For getting proper date, do something like this .

var ss = new DateTime (2005,01,01,0,0,0); //use this date in linq query

Hope it will help you.

Sign up to request clarification or add additional context in comments.

2 Comments

here why sql taking Null values when i enter through sql query Like select * from Employees where DataofJoin ='2005-01-01 00:00:00.000' its given me Exeact ans
because interpretation of date is been changed from Linq to sql , its not as you want it to be. Let me Update the answer to help you out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.