1

컨트롤러의이 메소드에 게시 된 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를 전달함으로써 이러한 오류를 피할 수 있다고 생각했습니다.

내가 뭘 잘못하고 있니?

+0

당신은 의존성 삽입 컨테이너를 사용 봐야한다 Ninject 또는 AutoFac과 같은 자신이 직접 만들지 않기 때문에 저장소/컨텍스트를 훨씬 쉽게 관리 할 수 ​​있습니다. – Dismissile

+0

문제와 관련이 없지만 생성 된 대신 전달 된 컨텍스트의 'UnitOfWorkUser'처분에주의해야합니다. 자신이 소유하지 않은 물건은 폐기해서는 안됩니다. – bhamlin

답변

0

는 asp.net의 MVC에서 UOW를 사용하는 것이 더 나은 방법이있다, 당신은 맥락에서 개체 수명의 여러 측면을 고려 해달라고, 그래서 나는 this article

0

읽기 제안이 나에게 매우 잘못된 보인다. 단위 작업 패턴의 목적은 하나의 객체에 모든 "작업"을 통합하는 것입니다. 당신이 DBContext를 배치하는 것 같은

  1. 당신은 dbcontext을 필요로하기 때문에 두 번

  2. , 당신은 대신 UOW 객체

    의 저장소에 dbcontext을 통과해서는 안 보이는 : 다음 코드를 사용하여 몇 가지 문제가 있습니다
  3. UserRepository에 대한 내부 참조가 필요할 수 있습니다. 리포지토리를 그룹화하고 모두 동일한 EF 컨텍스트 인스턴스를 공유하는 데 사용해야합니다. 샘플은,

    using (var uow = new UnitOfWorkUser(new Context())) 
        { 
         using (var _userRepo = new UserRepository(uow)) 
         { 
          _userRepo.InsertOrUpdate(newUser); 
          uow.Save(); 
         } 
        } 
    
  4. 여기

당신이 UOW를 사용하는 방법에 대한 예입니다 UnitOfWorkUser.UserRepo.Save (NEWUSER) 모양을

http://www.mattdurrant.com/ef-code-first-with-the-repository-and-unit-of-work-patterns/

관련 문제