问题
//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.
回答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();
回答2:
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.
来源:https://stackoverflow.com/questions/44650935/remove-a-record-with-child