2017-05-19 2 views
2

데이터 액세스 레이어 또는 단순히 DAL을 사용하여 데이터베이스에서 정보를 액세스하고 검색하는 방법을 알고 있지만 컨트롤러 내에서 DAL 데이터를 호출하는 방법을 모르겠습니다. 예를 들어, 내 DAL 내에서이 정적 클래스를 만들었지 만 내 컨트롤러에 전화하는 방법에 대해서는 확실하지 않습니다. 어떤 도움이나 지침도 인정 될 것입니다. DohvatiMetodu는 수업의 이름입니다.MVC 컨트롤러 내에서 데이터 액세스 레이어를 구현하는 방법

public static FormInputViewModel DohvatiMetodu() 
     { 
      var viewModel = new FormInputViewModel(); 
      var metoda = new List<Metoda>(); 
      var metodaList = new List<SelectListItem>(); 

      using (var db = new ApplicationDbContext()) 
      { 
       metoda = db.Metoda.ToList(); 
      } 

      foreach (var metod in metoda) 
      { 
       metodaList.Add(new SelectListItem() {Value = metod.Id.ToString(), Text = metod.Naziv}); 
      } 

      viewModel.KoristenaMetoda = metodaList; 


      return viewModel; 
+0

DAL은 데이터베이스에서 CRUD 작업을 수행하기위한 별도의 클래스 파일입니다. 'StaticClass.MethodName()'을 컨트롤러에서 직접 호출 할 수 있습니다. 컨트롤러에서 DAL에 액세스하는 데 아무런 제한이 없으며 MVC에서 규칙을 위반하지 않습니다. – ViVi

+0

정적 메서드 인 경우 범위에 올바른 네임 스페이스가 있다고 가정하면 'ClassName.MethodName'을 통해 액세스 할 수 있습니다. 물론, 요즘 정적 인 일을하지 않는 대신에 의존성 주입을 사용하여 클래스를 컨트롤러에 가져 오는 것이 일반적입니다. – mason

+0

정보를 주셔서 감사합니다,하지만 어떻게 종속성 주입의 형태로 보일까요? –

답변

5

사용자의 다양한 요구에 의하여 I가 전체 저장소 패턴 단순 CRUD 방법과 단계별 단계 코드를 업데이트 :

리포지토리 패턴 데이터 사이의 분리 층을 추가 응용 프로그램의 도메인 계층 또한 응용 프로그램의 데이터 액세스 부분을 더 쉽게 테스트 할 수 있습니다.

데이터베이스 공장 (IDatabaseFactory.cs) :

public interface IDatabaseFactory : IDisposable 
{ 
    Database_DBEntities Get(); 
} 

데이터베이스 공장 구현 (DatabaseFactory.cs) :

public class DatabaseFactory : Disposable, IDatabaseFactory 
{ 
    private Database_DBEntities dataContext; 
    public Database_DBEntities Get() 
    { 
     return dataContext ?? (dataContext = new Database_DBEntities()); 
    } 

    protected override void DisposeCore() 
    { 
     if (dataContext != null) 
      dataContext.Dispose(); 
    } 
} 

자료 인터페이스 (IRepository.cs) :

,451,515,
public interface IRepository<T> where T : class 
{ 
    void Add(T entity); 
    void Update(T entity); 
    void Detach(T entity); 
    void Delete(T entity); 
    T GetById(long Id); 
    T GetById(string Id); 
    T Get(Expression<Func<T, bool>> where); 
    IEnumerable<T> GetAll(); 
    IEnumerable<T> GetMany(Expression<Func<T, bool>> where); 
    void Commit(); 
} 

추상 클래스 (Repository.cs) :

public abstract class Repository<T> : IRepository<T> where T : class 
    { 
     private Database_DBEntities dataContext; 
     private readonly IDbSet<T> dbset; 
     protected Repository(IDatabaseFactory databaseFactory) 
     { 
      DatabaseFactory = databaseFactory; 
      dbset = DataContext.Set<T>(); 

     } 

     /// <summary> 
     /// Property for the databasefactory instance 
     /// </summary> 
     protected IDatabaseFactory DatabaseFactory 
     { 
      get; 
      private set; 
     } 

     /// <summary> 
     /// Property for the datacontext instance 
     /// </summary> 
     protected Database_DBEntities DataContext 
     { 
      get { return dataContext ?? (dataContext = DatabaseFactory.Get()); } 
     } 

     /// <summary> 
     /// For adding entity 
     /// </summary> 
     /// <param name="entity"></param> 
     public virtual void Add(T entity) 
     { 

      try 
      { 
       dbset.Add(entity); 
       // dbset.Attach(entity); 
       dataContext.Entry(entity).State = EntityState.Added; 
       int iresult = dataContext.SaveChanges(); 
      } 
      catch (UpdateException ex) 
      { 

      } 
      catch (DbUpdateException ex) //DbContext 
      { 

      } 
      catch (Exception ex) 
      { 
       throw ex; 
      } 

     } 

     /// <summary> 
     /// For updating entity 
     /// </summary> 
     /// <param name="entity"></param> 
     public virtual void Update(T entity) 
     { 
      try 
      { 
       // dbset.Attach(entity); 
       dbset.Add(entity); 
       dataContext.Entry(entity).State = EntityState.Modified; 
       int iresult = dataContext.SaveChanges(); 
      } 
      catch (UpdateException ex) 
      { 
       throw new ApplicationException(Database_ResourceFile.DuplicateMessage, ex); 
      } 
      catch (DbUpdateException ex) //DbContext 
      { 
       throw new ApplicationException(Database_ResourceFile.DuplicateMessage, ex); 
      } 
      catch (Exception ex) { 
       throw ex; 
      } 
     } 



     /// <summary> 
     /// for deleting entity with class 
     /// </summary> 
     /// <param name="entity"></param> 
     public virtual void Delete(T entity) 
     { 
      dbset.Remove(entity); 
      int iresult = dataContext.SaveChanges(); 
     } 


     //To commit save changes 
     public void Commit() 
     { 
      //still needs modification accordingly 
      DataContext.SaveChanges(); 
     } 

     /// <summary> 
     /// Fetches values as per the int64 id value 
     /// </summary> 
     /// <param name="id"></param> 
     /// <returns></returns> 
     public virtual T GetById(long id) 
     { 
      return dbset.Find(id); 
     } 

     /// <summary> 
     /// Fetches values as per the string id input 
     /// </summary> 
     /// <param name="id"></param> 
     /// <returns></returns> 
     public virtual T GetById(string id) 
     { 
      return dbset.Find(id); 
     } 

     /// <summary> 
     /// fetches all the records 
     /// </summary> 
     /// <returns></returns> 
     public virtual IEnumerable<T> GetAll() 
     { 
      return dbset.AsNoTracking().ToList(); 
     } 

     /// <summary> 
     /// Fetches records as per the predicate condition 
     /// </summary> 
     /// <param name="where"></param> 
     /// <returns></returns> 
     public virtual IEnumerable<T> GetMany(Expression<Func<T, bool>> where) 
     { 
      return dbset.Where(where).ToList(); 
     } 

     /// <summary> 
     /// 
     /// </summary> 
     /// <param name="entity"></param> 
     public void Detach(T entity) 
     { 
      dataContext.Entry(entity).State = EntityState.Detached; 
     } 

     /// <summary> 
     /// fetches single records as per the predicate condition 
     /// </summary> 
     /// <param name="where"></param> 
     /// <returns></returns> 
     public T Get(Expression<Func<T, bool>> where) 
     { 
      return dbset.Where(where).FirstOrDefault<T>(); 
     } 

    } 

지금 요점은 컨트롤러에서이 저장소 패턴에 액세스하려면 어떻게 여기에 우리가 간다 :

1. 사용자 모델 :

public partial class User 
{ 
     public int Id { get; set; } 
     public string Name { get; set; } 
} 

2. 지금 당신은 당신의 UserModel의 저장소 클래스를 만들 수있는 모든 CRUD 방법과

public class UserRepository : Repository<User>, IUserRepository 
{ 
    private Database_DBEntities dataContext; 

    protected IDatabaseFactory DatabaseFactory 
    { 
     get; 
     private set; 
    } 

    public UserRepository(IDatabaseFactory databaseFactory) 
     : base(databaseFactory) 
    { 
     DatabaseFactory = databaseFactory; 
    } 

    protected Database_DBEntities DataContext 
    { 
     get { return dataContext ?? (dataContext = DatabaseFactory.Get()); } 
    } 

    public interface IUserRepository : IRepository<User> 
    { 
    } 
} 

3. 이제 UserService 인터페이스 (IUserService.cs)를 만들 수 있습니다

public interface IUserService 
{ 

    #region User Details 
    List<User> GetAllUsers(); 
    int SaveUserDetails(User Usermodel); 
    int UpdateUserDetails(User Usermodel); 
    int DeleteUserDetails(int Id); 
    #endregion 

} 

4. 이제 모든 CRUD 메서드를 사용하여 UserService 인터페이스 (UserService.cs)를 만들어야합니다.

5. 이제 모든 저장소 패턴 설정하면 사용자의 컨트롤러에있는 모든 데이터에 액세스 할 수 있습니다 :

//Here is the User Controller 
public class UserProfileController : Controller 
{ 

    IUserService _userservice; 
    public CustomerProfileController(IUserService userservice) 
    { 
     this._userservice = userservice; 
    } 

    [HttpPost] 
    public ActionResult GetAllUsers(int id) 
    { 
    User objUser=new User(); 

    objUser = _userservice.GetAllUsers().Where(x => x.Id == id).FirstOrDefault(); 

    } 
} 

건배를!

관련 문제