基本上,我正在尝试关注Chris Pratt的“真正的通用存储库”(http://cpratt.co/truly-generic-repository/),但不知道如何处理该通用存储库中的多对多关系。我不想将Attach方法添加到接口,然后从我的服务层调用它(我将Chris Pratt的IRepository称为IService),基本上所有的服务功能都将调用Service:IService。换句话说,我不想在PersonService中调用Attach方法,我希望Service.cs中的Create / Update方法(继承IRepository / IService)自动处理多对多,而不需要消费者的参与(即PersonService.cs)。
有什么想法吗?
我目前的代码如下,我不知道如何使用Chris Pratt的存储库实现相同的效果。
public int AddPerson(Person person)
{
using (var dbContext = new MyContext("myConnString"))
{
// Attaching Hobbies
person.Hobbies.ToList().ForEach(x => dbContext.Hobbies.Attach(x));
dbContext.People.Add(person);
dbContext.SaveChanges();
return person.PersonId;
}
}
public void UpdatePerson(Person person)
{
using (var dbContext = new MyContext("myConnString"))
{
// Loading existing entity to compare
Person existingPerson = FindPersonBy(true, x => x.PersonId == person.PersonId, new string[] { "Hobbies", "Gender" });
dbContext.People.Attach(existingPerson);
dbContext.Entry(existingPerson).CurrentValues.SetValues(person);
// Updating Person.Hobbies
var deletedHobbies = existingPerson.Hobbies.ExceptBy(person.Hobbies, x => x.HobbyId).ToList();
deletedHobbies.ForEach(x => existingPerson.Hobbies.Remove(x));
var addedHobbies = person.Hobbies.ExceptBy(existingPerson.Hobbies, x => x.HobbyId).ToList();
addedHobbies.ForEach(x => { dbContext.Hobbies.Attach(x); existingPerson.Hobbies.Add(x); });
// Saving Transaction
dbContext.SaveChanges();
}
}