컨트롤러의이 메소드에 게시 된 NewUserViewModel에 바인딩 된보기가 있습니다.작업 단위 및 저장소 패턴을 가져 오는 중 문제가 발생했습니다.
[HttpPost]
public ActionResult NewUser(NewUserViewModel newUser)
{
var user = new User();
user.Id = newUser.Id;
user.Email = newUser.Email;
//more mapping hidden for brevity
//here is where the trouble starts
_userService.AddNewUser(user);
return RedirectToAction("Users");
}
_userService는 _userService에 AddNewUser 방법은 다음과 같습니다이
private IUserService _userService;
public ControllerName()
{
_userService = new UserService();
}
같은 컨트롤러의 생성자에서 인스턴스화 개인 필드에있다.
public void AddNewUser(User newUser)
{
using (var uow = new UnitOfWorkUser(new Context()))
{
using (var _userRepo = new UserRepository(uow))
{
_userRepo.InsertOrUpdate(newUser);
uow.Save();
}
}
}
UserRepository의 생성자는 다음과 같습니다.
private Context _context;
public UserRepository(UnitOfWorkUser unitOfWork)
{
_context = unitOfWork.Context;
}
및 unitOfWorkLooks는 이와 유사합니다.
public class UnitOfWorkUser :IDisposable, IUnitOfWork
{
private readonly Context _context;
public UnitOfWorkUser(Context context = null)
{
_context = context ?? new Context();
}
public int Save()
{
return _context.SaveChanges();
}
internal Context Context
{
get { return _context; }
}
public void Dispose()
{
_context.Dispose();
}
}
_userRepo의 InsertOrUpdate 메소드는 다음과 같습니다.
public virtual void InsertOrUpdate(User user)
{
if (user.Id == default(int))
{
_context.Users.Add(user);
}
else
{
_context.Entry(user).State = System.Data.EntityState.Modified;
}
}
나는 _context.Users.Add (사용자)에 도착하면; 위의 메서드에서이 오류가 발생합니다.
IEntityChangeTracker의 여러 인스턴스에서 엔터티 개체를 참조 할 수 없습니다.
UserRepository의 생성자에서 UnitOfWork Object를 사용하여 Context를 전달함으로써 이러한 오류를 피할 수 있다고 생각했습니다.
내가 뭘 잘못하고 있니?
당신은 의존성 삽입 컨테이너를 사용 봐야한다 Ninject 또는 AutoFac과 같은 자신이 직접 만들지 않기 때문에 저장소/컨텍스트를 훨씬 쉽게 관리 할 수 있습니다. – Dismissile
문제와 관련이 없지만 생성 된 대신 전달 된 컨텍스트의 'UnitOfWorkUser'처분에주의해야합니다. 자신이 소유하지 않은 물건은 폐기해서는 안됩니다. – bhamlin