0
       //Delete Last Record which has income
        var itemToRemove = db.People.LastOrDefault(p => p.Incomes.Any());
        db.Incomes.RemoveRange(itemToRemove.Incomes);
        db.People.Remove(itemToRemove);

it gives me this error

An unhandled exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll

Additional information: LINQ to Entities does not recognize the method 'EF_Examples_02.Person LastOrDefault[Person]

I have two Tables(Person,Income) each person can have n incomes . two Tables have relationship.

Community
  • 1
  • 1
Mansoure
  • 69
  • 5
  • 4
    it cannot translate `LastOrDefault` to an SQL Statement. There is no equivalent! [this answer](https://stackoverflow.com/a/7259649/5174469) sheds more light on it – Mong Zhu Jun 20 '17 at 10:49

2 Answers2

1

The problem here is that LastOrDefault isn't translated to a SQL statement.

Basically you have 2 options:

Fetch all the data first:

//the tolist will fetch the data from the database
db.People.ToList().LastOrDefault(p => p.Incomes.Any()); 

Or order by descending, maybe by id:

db.People.Where(p => p.Incomes.Any()).OrderByDescending(c => c.Id).FirstOrDefault();

As for a hybrid option:

db.People.Where(p => p.Incomes.Any()).ToList().LastOrDefault();
Stefan
  • 17,448
  • 11
  • 60
  • 79
  • thanks a lot. these codes remove the last person who has income. but don't remove their incomes from income table. db.Incomes.RemoveRange(itemToRemove.Incomes); dosent work – Mansoure Jun 25 '17 at 08:19
  • Do you get an error? – Stefan Jun 25 '17 at 14:51
  • when I closed visual studio and opened it again ,it worked correctly,thank you very much my friend. – Mansoure Jun 29 '17 at 06:16
1

The problem is in LastOrDefault. Ling-to-Entities does not support it.

You have to be aware that several Enumerable functions can't be performed as Queryable.

MSDN Supported and Unsupported LINQ Methods (LINQ to Entities)

LastOrDefault: Not supported

Luckily, FirstOrDefault is supported.

Normally the result is fairly unpredictable if you search for First / Last without any ordering.

Consider specifying for yourself what you would call the Last element, after that it is easy to order in descending order, so it would be your First element, which can be queried.

Harald Coppoolse
  • 28,834
  • 7
  • 67
  • 116