使用GenericRepository插入方法

时间:2015-11-06 09:38:03

标签: c# entity-framework asp.net-mvc-4 razor unit-of-work

我尝试插入一个带有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; } 




    }

插入方法:

public ActionResult Create()     {

    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();
}

但是我会在Razor Create方法中得到这个错误:

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();

我得到一个null refenect异常

1 个答案:

答案 0 :(得分: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");