2016-03-24 3 views
0

Я прочитал тонну сообщений с этой проблемой, но я думаю, что мой немного отличается.Получение «Тип объекта <type> не является частью модели для текущего контекста».

Недавно я удалил свой файл EDMX и переключение в Code First и я имею вопросы получаю эту ошибку:

The entity type User is not part of the model for the current context.

Я знаю, что EntityRepository работает хорошо, потому что он работал отлично с методом EDMX. Но по какой-то причине мой контент не привязывает модели.

IEntityRepository

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Linq.Expressions; 
using System.Text; 
using System.Threading.Tasks; 
using Pronto.Data.Models; 

namespace Data.Repositories.Interfaces 
{ 
    public interface IEntityRepository<TEntity> : IDisposable 
    { 
     System.Threading.Tasks.Task<TEntity> GetByIdAsync(int id); 
     System.Threading.Tasks.Task<TEntity> GetByIdAsync(Guid id); 
     System.Threading.Tasks.Task<TEntity> GetByIdAsync(string id); 

     IQueryable<TEntity> SearchFor(Expression<Func<TEntity, bool>> predicate); 
     IQueryable<TEntity> GetAll(); 
     IQueryable<TEntity> GetAllIncluding(params Expression<Func<TEntity, object>>[] includeProperties); 

     System.Threading.Tasks.Task<TEntity> InsertAsync(TEntity entity); 
     System.Threading.Tasks.Task<List<TEntity>> InsertAllAsync(List<TEntity> entities); 

     System.Threading.Tasks.Task UpdateAsync(TEntity entity); 
     System.Threading.Tasks.Task UpdateAllAsync(List<TEntity> entities); 

     System.Threading.Tasks.Task DeleteAsync(TEntity entity); 
     System.Threading.Tasks.Task DeleteAllAsync(List<TEntity> entities); 

    } 

} 

EntityRepository

using System; 
using System.Collections.Generic; 
using System.Data.Entity; 
using System.Linq; 
using System.Linq.Expressions; 
using System.Text; 
using Pronto.Data.Repositories.Interfaces; 
using System.Data.Entity.Validation; 
using Errors; 
using System.Transactions; 
using LinqKit; 

namespace Data.Repositories 
{ 
    public class EntityRepository<TEntity> : IEntityRepository<TEntity> where TEntity : class 
    { 
     protected DbSet<TEntity> dbSet; 

     private readonly DbContext dc; 

     public EntityRepository() 
     { 
      var connectionString = Programs.ProntoUdl.GetDBConnectionString(); //Utility.Config.GetEntityDbConnection(); 
      dc = new DbContext(connectionString); 
      dbSet = dc.Set<TEntity>(); 
     } 

     public void FixEntityFrameworkSqlServerDllIssueNotDeployingForReleaseBuild() 
     { 
      //=============================================================================================== 
      //this line needs to be here to force the release version to deply the EntityFramework.SqlServer.dll 
      //=============================================================================================== 
      bool instanceExists = System.Data.Entity.SqlServer.SqlProviderServices.Instance != null; 
      //=============================================================================================== 
      //=============================================================================================== 
      //=============================================================================================== 
     } 

#region ==== GET ==== 

     public TEntity GetById(int id) 
     { 
      return dbSet.Find(id); 
     } 

     public TEntity GetById(Guid id) 
     { 
      return dbSet.Find(id); 
     } 

     public TEntity GetById(string id) 
     { 
      return dbSet.Find(id); 
     } 

     public async System.Threading.Tasks.Task<TEntity> GetByIdAsync(int id) 
     { 
      return await dbSet.FindAsync(id); 
     } 

     public async System.Threading.Tasks.Task<TEntity> GetByIdAsync(Guid id) 
     { 
      return await dbSet.FindAsync(id); 
     } 

     public async System.Threading.Tasks.Task<TEntity> GetByIdAsync(string id) 
     { 
      return await dbSet.FindAsync(id); 
     } 

     public IQueryable<TEntity> SearchFor(Expression<Func<TEntity, bool>> predicate) 
     { 
      using (var txs = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted })) 
      { 
       return dbSet.Where(predicate); 
      } 
     } 

     public IQueryable<TEntity> SearchFor(Expression<Func<TEntity, bool>> predicate, params Expression<Func<TEntity, object>>[] includeProperties) 
     { 
      using (var txs = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted })) 
      { 
       IQueryable<TEntity> query = dbSet; 

       if (includeProperties != null) 
       { 
        query = includeProperties.Aggregate(query, (current, include) => current.Include(include)); 
       } 
       if (predicate != null) 
       { 
        query = query.AsExpandable().Where(predicate); 
       } 
       return query; 
      } 
     } 

     public IQueryable<TEntity> GetAll() 
     { 
      using (var txs = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted })) 
      { 
       return dbSet; 
      } 
     } 

     public IQueryable<TEntity> GetAllIncluding(params Expression<Func<TEntity, object>>[] includeProperties) 
     { 
      using (var txs = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted })) 
      { 
       foreach (var includedProperty in includeProperties) 
       { 
        dbSet.Include(includedProperty).Load(); 
       } 

       return dbSet; 
      } 
     } 

#endregion 

#region ==== INSERT ==== 

     public async System.Threading.Tasks.Task<TEntity> InsertAsync(TEntity entity) 
     { 
      try 
      { 
       dbSet.Add(entity); 
       await dc.SaveChangesAsync(); 
      } 
      catch (Exception ex) 
      { 
       EventLogger.WriteToLog(ex.ToString(), "ProntoData"); 
       if (ex is DbEntityValidationException) 
       { 
        DbEntityValidationException e = (DbEntityValidationException)ex; 
        StringBuilder errorMessage = new StringBuilder(); 
        foreach (var eve in e.EntityValidationErrors) 
        { 
         errorMessage.AppendFormat("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State); 
         foreach (var ve in eve.ValidationErrors) 
         { 
          errorMessage.AppendFormat("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage); 
         } 
        } 
        throw new Exception(errorMessage.ToString()); 
       } 
       throw; 
      } 

      return entity; 
     } 

     public async System.Threading.Tasks.Task<List<TEntity>> InsertAllAsync(List<TEntity> entities) 
     { 
      try 
      { 
       entities.ForEach(x => dbSet.Add(x)); 
       await dc.SaveChangesAsync(); 
      } 
      catch (Exception ex) 
      { 
       EventLogger.WriteToLog(ex.ToString(), "ProntoData"); 
       if (ex is DbEntityValidationException) 
       { 
        DbEntityValidationException e = (DbEntityValidationException)ex; 
        StringBuilder errorMessage = new StringBuilder(); 
        foreach (var eve in e.EntityValidationErrors) 
        { 
         errorMessage.AppendFormat("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State); 
         foreach (var ve in eve.ValidationErrors) 
         { 
          errorMessage.AppendFormat("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage); 
         } 
        } 
        throw new Exception(errorMessage.ToString()); 
       } 
       throw; 
      } 

      return entities; 
     } 

#endregion 

#region ==== UPDATE ==== 

     public async System.Threading.Tasks.Task UpdateAsync(TEntity entity) 
     { 
      dc.Entry(entity).State = EntityState.Modified; 
      await dc.SaveChangesAsync(); 
     } 

     public async System.Threading.Tasks.Task UpdateAllAsync(List<TEntity> entities) 
     { 
      try 
      { 
       entities.ForEach(x => dc.Entry(x).State = EntityState.Modified); 
       await dc.SaveChangesAsync(); 
      } 
      catch (Exception ex) 
      { 
       EventLogger.WriteToLog(ex.ToString(), "ProntoData"); 
       if (ex is DbEntityValidationException) 
       { 
        DbEntityValidationException e = (DbEntityValidationException)ex; 
        StringBuilder errorMessage = new StringBuilder(); 
        foreach (var eve in e.EntityValidationErrors) 
        { 
         errorMessage.AppendFormat("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State); 
         foreach (var ve in eve.ValidationErrors) 
         { 
          errorMessage.AppendFormat("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage); 
         } 
        } 
        throw new Exception(errorMessage.ToString()); 
       } 
       throw; 
      } 
     } 

#endregion 

#region ==== DELETE ==== 

     public async System.Threading.Tasks.Task DeleteAsync(TEntity entity) 
     { 
      dbSet.Remove(entity); 
      await dc.SaveChangesAsync(); 
     } 

     public async System.Threading.Tasks.Task DeleteAllAsync(List<TEntity> entities) 
     { 
      try 
      { 
       entities.ForEach(x => dbSet.Remove(x)); 
       await dc.SaveChangesAsync(); 
      } 
      catch (Exception ex) 
      { 
       EventLogger.WriteToLog(ex.ToString(), "ProntoData"); 
       if (ex is DbEntityValidationException) 
       { 
        DbEntityValidationException e = (DbEntityValidationException)ex; 
        StringBuilder errorMessage = new StringBuilder(); 
        foreach (var eve in e.EntityValidationErrors) 
        { 
         errorMessage.AppendFormat("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State); 
         foreach (var ve in eve.ValidationErrors) 
         { 
          errorMessage.AppendFormat("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage); 
         } 
        } 
        throw new Exception(errorMessage.ToString()); 
       } 
       throw; 
      } 
     } 

#endregion 

     public void Dispose() 
     { 
      dc.Dispose(); 
     } 

    } 
} 

DbContext

namespace Pronto.Data.Models 
{ 
    using System; 
    using System.Data.Entity; 
    using System.ComponentModel.DataAnnotations.Schema; 
    using System.Linq; 

    public partial class Pronto : DbContext 
    { 
     public Pronto() 
      : base(Programs.ProntoUdl.GetDBConnectionString()) 
     { 
      //this.Configuration.LazyLoadingEnabled = false; 
     } 
     public virtual DbSet<User> Users { get; set; } 

     protected override void OnModelCreating(DbModelBuilder modelBuilder) 
     { 

      modelBuilder.Entity<User>().ToTable("Users"); 

      modelBuilder.Entity<User>() 
       .Property(e => e.PasswordHashed) 
       .IsUnicode(false); 
     } 
    } 
} 

Тест

using System; 
using Microsoft.VisualStudio.TestTools.UnitTesting; 
using Pronto.Data.Models; 
using Pronto.Data.Repositories; 
using System.Collections.Generic; 
using System.Linq; 

namespace ProntoDataTests 
{ 
    [TestClass] 
    public class EntityRepositoryTests 
    { 
     [TestMethod] 
     public async System.Threading.Tasks.Task GetByIdTest() 
     { 
      var repo = new EntityRepository<User>(); 
      User user = await repo.GetByIdAsync(1); 
      Assert.IsNotNull(user); 
     } 
    } 
} 
+3

'dc = new DbContext (connectionString);' должен быть 'новым Pronto' (ваш ** конкретный ** класс, основанный на DbContext) –

+0

Ahh - делает полный смысл! Я попробую. – RichC

+0

Да, это заставило меня пройти мимо этой ошибки (и дальше к следующей) - бросьте это как ответ, и я помету его «принятым» для вас. – RichC

ответ

1

Проблема эта линия

dc = new DbContext(connectionString); 

Вы создаете общий DbContext который, конечно, не содержит какой-либо объект.

Вместо этого вы должны создать экземпляр вашего конкретного DbContext производного класса

dc = new Pronto(connectionString); 

Примечание: Вы должны добавить другой конструктор для вашего Pronto класса, который принимает строку подключения.