I have an entity Person
, which has a related entity Hobby
. This is a many to many relationship where a person can have several hobbies, and a hobby can be associated with many people. I want to create a ViewModel
that allows new hobbies to be added and/or existing hobbies to be removed from a given Person entity.
The code below works, but I imagine it is rather inefficient.
var newHobbies = new List<Hobby>();
foreach (Hobby hobby in vm.Hobbies)
{
var originalHobby = db.Hobbies.Find(hobby.HobbyID);
newHobbies.Add(originalHobby);
}
originalPerson.Hobbies = newHobbies;
I prefer to do something like this:
var newHobbies = db.Hobbies.Where(x => vm.Hobbies.All(y => x.HobbyID == y.HobbyID)).ToList();
originalPerson.Hobbies = newHobbies;
But I get an error:
Only primitive types or enumeration types are supported in this context.
How can I update related data without going to the database multiple times?
答案 0 :(得分:1)
消息说你不能在LINQ-to-Entities查询中使用vm.Hobbies
,只能使用原始类型。这就是你能做的:
var hobbyIds = vm.Hobbies.Select(h => h.HobbyId).ToList();
var newHobbies = db.Hobbies.Where(x => hobbyIds.Contains(x.HobbyID)).ToList();
答案 1 :(得分:1)
要避免该异常,您可以先从vm.Hobbies
集合中选择ID,然后再过滤您需要的爱好:
var Ids=vm.Hobbies.Select(x=>x.HobbyID);
var newHobbies = db.Hobbies.Where(x => Ids.Contains(x.HobbyID)).ToList();
// another option could be: db.Hobbies.Where(x => Ids.Any(id=>id==x.HobbyID)).ToList();
originalPerson.Hobbies = newHobbies;
答案 2 :(得分:0)
The overall construction would be like such:
Hobby
passing a Hobby
entity back as part of the actionPerson
and Hobby
Hobby
entity to the collection in Person
In general EF and MVC are much easier to work with when you try to interact with your entities as whole entities and don't try to micromanage yourself things such as IDs, entity hydration, and so on.
答案 3 :(得分:0)
You could join by ID instead of fetching data from the DB:
originalPerson.Hobbies = db.Hobbies.Join(vm.Hobbies, h => h.ID,
v => v.HobbyID, (h, v) => h).ToList();