获取“实体类型<type>不是当前上下文模型的一部分。”

时间:2016-03-24 18:51:45

标签: c# entity-framework ef-code-first

我已经通过大量的帖子阅读了这个问题,但我认为我的情况有点不同。

我最近删除了我的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);
        }
    }
}

1 个答案:

答案 0 :(得分:1)

问题在于这一行

dc = new DbContext(connectionString);

您正在创建通用DbContext,当然不包含任何实体。

相反,您应该创建具体DbContext派生类

的实例
dc = new Pronto(connectionString);

注意:您需要向接受连接字符串的Pronto类添加另一个构造函数。