简体   繁体   English

列表中不存在的数据库中存在的记录

[英]records that exist in the database that don't exist in the list

I have in database table Gifts with records, for example: 我在数据库表“ Gifts”中有记录,例如:

Id: 1, Name: A
Id: 2, Name: B
Id: 3, Name: C

In IEnumerable<Gift> gifts I have elements from user after modification, for example: IEnumerable<Gift> gifts ,修改后我具有来自用户的元素,例如:

Id: 1, Name: A_update
Id: 3, Name: C_update
Id: 0, Name: D_new

Now I would like records that exist in the database that don't exist in the list - so in this example it should be one record: 现在,我希望数据库中存在的记录不存在于列表中-因此在此示例中,它应该是一个记录:

Id: 2, Name: B

How can I do that because below code doesn't work: 我怎么做,因为下面的代码不起作用:

List<Gifts> result = db.Gifts.Where(x => !gifts.Select(y => y.Id).Contains(x.Id)).ToList();

Unable to create a constant value of type 'MyProject.Models.Gift'. 无法创建类型为'MyProject.Models.Gift'的常量值。 Only primitive types or enumeration types are supported in this context. 在此上下文中仅支持原始类型或枚举类型。

This is a limitation of Entity Framework. 这是实体框架的限制。 In only supports using some specific data types in the expressions. In仅支持在表达式中使用某些特定的数据类型。

If you use Entity Framework 4.0 or later you can use this workaround: 如果您使用Entity Framework 4.0或更高版本,则可以使用以下解决方法:

int[] giftIds = gifts.Select(y => y.Id);
List<Gifts> result = db.Gifts.Where(x => !giftIds.Contains(x.Id)).ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM