2016-03-24 23 views
0

私はいくつかの問題の記事を読みましたが、私は少し違いますと思います。"エンティティタイプ<type>は、現在のコンテキストのモデルの一部ではありません。"

私は最近、私のEDMXファイルを削除し、コードファーストへの切り替えと、私はこのエラーを取得して問題を抱えている:

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

それはEDMX方法でうまく働いたので、私はEntityRepositoryが正常に動作します知っています。しかし何らかの理由で私のコンテンツはモデルに付いていません。

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

問題は、この行は、あなたはもちろん、任意のエンティティが含まれていない一般的なDbContextを作成している

dc = new DbContext(connectionString); 

です。

代わりに、あなたはあなたの具体的なDbContext派生クラスの

dc = new Pronto(connectionString); 

注インスタンスを作成する必要があります:あなたは、接続文字列を受け入れ、あなたのProntoクラスに別のコンストラクタを追加する必要があります。

関連する問題