简体   繁体   中英

records that exist in the database that don't exist in the list

I have in database table Gifts with records, for example:

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:

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'. 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.

If you use Entity Framework 4.0 or later you can use this workaround:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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