2015-11-06 4 views
1

Я пытаюсь вставить объект с genericrepository:метод Insert с GenericRepository

У меня есть это:

GenericRepository:

public class GenericRepository<TEntity> where TEntity : class 
    { 
     internal LolaBikeContext context; 
     internal DbSet<TEntity> dbSet; 

     public GenericRepository(LolaBikeContext context) 
     { 
      this.context = context; 
      this.dbSet = context.Set<TEntity>(); 
     } 

     public virtual IEnumerable<TEntity> GetWithRawSql(string query, params object[] parameters) 
     { 
      return dbSet.SqlQuery(query, parameters).ToList(); 
     } 

     public virtual IEnumerable<TEntity> Get(
      Expression<Func<TEntity, bool>> filter = null, 
      Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null, 
      string includeProperties = "") 
     { 
      IQueryable<TEntity> query = dbSet; 

      if (filter != null) 
      { 
       query = query.Where(filter); 
      } 

      foreach (var includeProperty in includeProperties.Split 
       (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) 
      { 
       query = query.Include(includeProperty); 
      } 

      if (orderBy != null) 
      { 
       return orderBy(query).ToList(); 
      } 
      else 
      { 
       return query.ToList(); 
      } 
     } 

     public virtual TEntity GetByID(object id) 
     { 
      return dbSet.Find(id); 
     } 

     public virtual void Insert(TEntity entity) 
     { 
      dbSet.Add(entity); 
     } 

     public virtual void Delete(object id) 
     { 
      TEntity entityToDelete = dbSet.Find(id); 
      Delete(entityToDelete); 
     } 

     public virtual void Delete(TEntity entityToDelete) 
     { 
      if (context.Entry(entityToDelete).State == EntityState.Detached) 
      { 
       dbSet.Attach(entityToDelete); 
      } 
      dbSet.Remove(entityToDelete); 
     } 

     public virtual void Update(TEntity entityToUpdate) 
     { 
      dbSet.Attach(entityToUpdate); 
      context.Entry(entityToUpdate).State = EntityState.Modified; 
     } 
    } 

UnitOfWork:

public class UnitOfWork : IDisposable 
    { 
     private LolaBikeContext context = new LolaBikeContext(); 
     private GenericRepository<UserProfile> userRepository; 
     private GenericRepository<Route> routeRepository; 
     private GenericRepository<Climb> climbRepository; 
     private GenericRepository<Country> countryRepository; 
     private GenericRepository<Difficult> difficultRepository; 
     private GenericRepository<ClimbViewModel> climbViewModelRepository; 


     public GenericRepository<UserProfile> UserRepository 
     { 


      get 
      { 

       if (this.userRepository == null) 
       { 
        this.userRepository = new GenericRepository<UserProfile>(context); 
       } 
       return userRepository; 
      } 
     } 

     public GenericRepository<Route> RouteRepository 
     { 
      get 
      { 
       if (this.routeRepository == null) 
       { 
        this.routeRepository = new GenericRepository<Route>(context); 
       } 
       return routeRepository; 
      } 
     } 

     public GenericRepository<Climb>ClimbRepository 
     { 
      get 
      { 

       if (this.climbRepository == null) 
       { 
        this.climbRepository = new GenericRepository<Climb>(context); 
       } 
       return this.climbRepository; 
      } 

     } 

     public GenericRepository<ClimbViewModel> ClimbViewModelRepository 
     { 
      get 
      { 
       if (climbViewModelRepository == null) 
       { 
        this.climbViewModelRepository = new GenericRepository<ClimbViewModel>(context); 
       } 
       return this.climbViewModelRepository; 

      } 
     } 

     public GenericRepository<Country>CountryRepository 
     { 

      get 
      { 

       if (this.countryRepository != null) 
       { 
        countryRepository = new GenericRepository<Country>(context); 
       } 
       return this.countryRepository; 
      } 
     } 

     public GenericRepository<Difficult>DifficultRepository 
     { 


      get 
      { 

       if (difficultRepository != null) 
       { 
        difficultRepository = new GenericRepository<Difficult>(context); 
       } 
       return this.difficultRepository; 
      } 

     } 




     public void Save() 
     { 
      context.SaveChanges(); 
     } 

     private bool disposed = false; 

     protected virtual void Dispose(bool disposing) 
     { 
      if (!this.disposed) 
      { 
       if (disposing) 
       { 
        context.Dispose(); 
       } 
      } 
      this.disposed = true; 
     } 

     public void Dispose() 
     { 
      Dispose(true); 
      GC.SuppressFinalize(this); 
     } 
    } 

CLASS Climb:

public class Climb 
    { 

     [Key] 
     public int climbID { get; set; }  
     public string Name { get; set; } 
     public int Points { get; set; } 


     public int? UserProfileID { get; set; } 
     public int? CountryId { get; set; } 
     public int? DifficultId { get; set; } 



     public virtual UserProfile userProfile { get; set; } 
     public virtual Country country { get; set; } 
     public virtual Difficult difficult { get; set; } 




    } 

метод вставки:

общественного ActionResult Создать() {

var queryCountry = unitOfWork.ClimbRepository.Get(
     orderBy: q => q.OrderBy(c => c.country.country_name)); 
    var queryDifficult = unitOfWork.ClimbRepository.Get(
     orderBy: qd => qd.OrderBy(d => d.difficult.DifficultName)); 

    ViewBag.CountryId = new SelectList(queryCountry, "CountryId", "country_name"); 
    ViewBag.DifficultId = new SelectList(queryDifficult, "DifficultId", "DifficultName"); 
    return View(); 
} 

Но тогда я получаю эту ошибку в бритве Создать метод:

An exception of type 'System.Web.HttpException' occurred in System.Web.dll but was not handled in user code 

Additional information: DataBinding: 'System.Data.Entity.DynamicProxies.Climb_0568B2C1C64C1C347E3DF33E87F37C8D672D9794887F77C523EB7B16E9399FCE' does not contain a property with the name 'country_name'. 

на этой линии :

<div class="form-group"> 

      <label class="control-label col-md-2" for="CountryID">Country</label> 
      @Html.DropDownList("CountryId", ViewBag.countries as SelectList, new { @class = "form-control", style = "width: 250px;" }) 
     </div> 

Спасибо

Если я пытаюсь это так:

var queryCountry = unitOfWork.CountryRepository.Get(
     orderBy: q => q.OrderBy(c => c.country_name)); 
    var queryDifficult = unitOfWork.ClimbRepository.Get(
     orderBy: qd => qd.OrderBy(d => d.difficult.DifficultName)); 

    ViewBag.CountryId = new SelectList(queryCountry, "CountryId", "country.country_name"); 
    ViewBag.DifficultId = new SelectList(queryDifficult, "DifficultId", "difficult.DifficultName"); 
    return View(); 

я получаю пустой refenect за исключением

+0

Somebody некоторые ideer? Спасибо – InfinityGoesAround

+0

Есть ли кто-нибудь ??? – InfinityGoesAround

+0

?? мне никто не может советовать? – InfinityGoesAround

ответ

1

ошибка говорит вам, что это неправильно. queryCountry не содержит «country_name». «country_name» является собственностью страны, а не Climb. Попробуйте

ViewBag.CountryId = new SelectList(queryCountry, "CountryId", "country.country_name"); 

Вы будете иметь те же проблемы с следующей строки кода, а также, должно быть

ViewBag.DifficultId = new SelectList(queryDifficult, "DifficultId", "difficult.DifficultName"); 

Включите страну в вашем Get() вызов:

var queryCountry = unitOfWork.ClimbRepository.Get(
    orderBy: q => q.OrderBy(c => c.country.country_name), 
    includeProperties: "country"); 
+0

Но проблема в том, что я получаю, что страны уже вставки поднимаются, а не список стран. – InfinityGoesAround

+0

Я редактирую сообщение – InfinityGoesAround

+0

. Мне кажется, вам нужно передать страну в качестве параметра include в вашем вызове Get. Мой Guess, если вы установили точку останова в строке ViewBag.CountryId, вы увидите, что query.country имеет значение NULL. Лично я бы сменил ваши включения на выражение >, или еще лучше, IEnumerable >>, см. Править для того, как я реализовал мой (спасибо https://genericunitofworkandrepositories.codeplex.com/) – garethb

Смежные вопросы