user3198329
user3198329

Reputation: 1

Error in data type linq

There is a request: "Take two older (max age) children and complete their stay in kindergarten"

var s = db.Child.Max(e => (DateTime.Today - e.Birthday));
foreach (var n in db.Child.Where(e => (DateTime.Today - e.Birthday) == s).Take(2))
db.DeleteObject(n);

"Birthday" - data type => "datetime".

Error: DbArithmeticExpression arguments must have a numeric common type

Where did I go wrong!?

Upvotes: 0

Views: 109

Answers (3)

Lawrence Thurman
Lawrence Thurman

Reputation: 677

pull you where statement out of the foreach statement and check your database DataType.

class Program
{
    static void Main(string[] args)
    {
            List<Test> Tests = new List<Test>();
            Tests.Add(new Test(new DateTime(2014, 01, 01)));
            Tests.Add(new Test(new DateTime(2013, 01, 01)));
            Tests.Add(new Test(new DateTime(2012, 01, 01)));
            Tests.Add(new Test(new DateTime(2011, 01, 01)));
            Tests.Add(new Test(new DateTime(2010, 01, 01)));
            Tests.Add(new Test(new DateTime(2009, 01, 01)));
            Tests.Add(new Test(new DateTime(2008, 01, 01)));


            var s = Tests.Max(e => (DateTime.Today - e.Birthday));
            var d =Tests.Where(e => (DateTime.Today - e.Birthday) == s).Take(2);

    }
}

public class Test
{
    public DateTime Birthday { get; set; }

    public Test(DateTime dateTime)
    {
        Birthday = dateTime;
    }
}

but I would think your logic is incorrect if you want the two oldest children. This is give you oldest children if their birthdates are the same, look at

var oldestChildren = db.Child.OrderBy(c => c.Birthday).Take(2).ToList();

Upvotes: 0

Suraj Singh
Suraj Singh

Reputation: 4059

EF do not supports arithmetic operations with DateTime.

var s = db.Child.Max(e => EntityFunctions.DiffDays(DateTime.Today - e.Birthday));

EntityFunctions

Upvotes: 0

Rapha&#235;l Althaus
Rapha&#235;l Althaus

Reputation: 60493

You overcomplicating things. The oldest children are the one... which are born first.

So

var oldestChildren = db.Child.OrderBy(c => c.Birthday).Take(2).ToList();

//if "complete they stay in kindergarten means delete
foreach (var child in oldestChildren)
   db.DeleteObject(child);

Upvotes: 2

Related Questions