2016-03-24 10 views
0

Bu sorunla birlikte bir ton gönderi okudum ama sanırım benimki biraz farklı. "Varlık türü <type>, geçerli içerik için modelin bir parçası değil."

Geçenlerde Kod Birinci benim edmx dosyası ve geçiş silinir ve bu hatayı almaya haiz konular değilim:

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

Ben EDMX yöntemi ile iyi çalıştı çünkü EntityRepository çalışıyor biliyorum. Ama bir sebepten dolayı içeriğim modelleri takmıyor.

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

Testi

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);' 'new Pronto' olmalıdır (sizin ** beton ** DbContext'ten türetilmiş sınıf) –

+0

Ahh - tam anlamıyla! Bunu deneyeceğim. – RichC

+0

Beni bu hatayı (ve bir sonrakine) aktaran evet - bunu bir cevap olarak atın ve sizin için "kabul ediyorum" olarak işaretleyeceğim. – RichC

cevap

1

sorunu bu hat

dc = new DbContext(connectionString); 

Elbette herhangi bir kuruluş içermeyen bir jenerik DbContext oluştururken olduğunu.

Bunun yerine, somut DbContext türetilmiş sınıfın

dc = new Pronto(connectionString); 

Not örneği oluşturmak olmalıdır: Bağlantı dizesini kabul edeceğini Pronto sınıfına başka yapıcısı eklemeniz gerekir.

İlgili konular