remove a record with child [duplicate]

久未见 提交于 2020-01-07 06:36:13

问题


       //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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!