存储库模式&工作单元 - 问题 - 超时错误

时间:2014-04-15 16:48:53

标签: c# entity-framework repository unit-of-work azure-sql-database

我实现了Repository Pattern&从Microsoft http://www.asp.net/mvc/tutorials/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application获得以下教程后的工作单元。问题是我经常遇到错误。

Inner exception error Time out

我的DbContext

    public class SsContext : DbContext
{

    public SsContext()
        : base("DefaultConnection")
    {
        ((IObjectContextAdapter) this).ObjectContext.CommandTimeout = 180;
    }

}

我的存储库模式

    public class GenericRepository<TEntity> where TEntity : class
{
    internal SsContext Context;
    internal DbSet<TEntity> DbSet;

    public GenericRepository(SsContext context)
    {
        this.Context = context;
        this.DbSet = context.Set<TEntity>();
    }

    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 Update(TEntity entityToUpdate)
    {
        var entry = this.Context.Entry(entityToUpdate);
        var key = this.GetPrimaryKey(entry);

        if (entry.State == EntityState.Detached)
        {
            var currentEntry = GetById(key);
            if (currentEntry != null)
            {
                var attachedEntry = Context.Entry(currentEntry);
                attachedEntry.CurrentValues.SetValues(entityToUpdate);
            }
            else
            {
                DbSet.Attach(entityToUpdate);
                Context.Entry(entityToUpdate).State = EntityState.Modified;
            }
        }


    }

    private object GetPrimaryKey(System.Data.Entity.Infrastructure.DbEntityEntry<TEntity> entry)
    {
        var myObject = entry.Entity;
        var property = myObject.GetType().GetProperties().FirstOrDefault(prop => Attribute.IsDefined(prop, typeof(KeyAttribute)));

        var stringReturnData = property.GetValue(myObject, null).ToString();

        Guid returningGuid;
        var ifItIsGuid = Guid.TryParse(stringReturnData, out returningGuid);
        if (ifItIsGuid)
        {
            return (Guid)property.GetValue(myObject, null);
        }

        int returningInt;
        var ifItIsInt = int.TryParse(stringReturnData, out returningInt);
        if (ifItIsInt)
        {
            return (int)property.GetValue(myObject, null);
        }

        long returningLong;
        var ifItIsLong = long.TryParse(stringReturnData, out returningLong);
        if (ifItIsLong)
        {
            return (long)property.GetValue(myObject, null);
        }

        return null;

    }

    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 class Uow : IDisposable
{
    private readonly SsContext _context = new SsContext();

    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //Course Category
    private GenericRepository<CourseCategory> _courseCategoryRepository;
    public GenericRepository<CourseCategory> CourseCategoryRepository
    {
        get
        {
            if (this._courseCategoryRepository == null)
            {
                this._courseCategoryRepository = new GenericRepository<CourseCategory>(_context);
            }

            return _courseCategoryRepository;
        }
    }
    //Course
    private GenericRepository<Course> _courseRepository;
    public GenericRepository<Course> CourseRepository
    {
        get
        {
            if (this._courseRepository == null)
            {
                this._courseRepository = new GenericRepository<Course>(_context);
            }

            return _courseRepository;
        }
    }

    //CourseType
    private GenericRepository<CourseType> _courseTypeRepository;
    public GenericRepository<CourseType> CourseTypeRepository
    {
        get
        {
            if (this._courseTypeRepository == null)
            {
                this._courseTypeRepository = new GenericRepository<CourseType>(_context);
            }

            return _courseTypeRepository;
        }
    }

    //The Save method calls SaveChanges on the database context.
    public void Save()
    {

        try
        {
            _context.SaveChanges();
        }
        catch (DbEntityValidationException dbEx)
        {
            foreach (var validationErrors in dbEx.EntityValidationErrors)
            {
                foreach (var validationError in validationErrors.ValidationErrors)
                {
                    Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                }
            }
        }

    }

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

我在Asp.Net Mvc中实现的方式

        public ActionResult Index(string id)
    {
        var model = new ViewModels.ClientViewModel.CourseClientViewModel();

        IEnumerable<Batch> batches = null;
        var user = _user;

            var course = _db.CourseRepository.DbSet.Include("CourseCategory")
                .Include("CourseLevel")
                .Include("Teacher")
                .Include("CourseModuleConnectors.Module")
                .Include("OnlineCourseSubscriptions")
                .Include("Batches")
                .FirstOrDefault(c => c.FriendlyUrl == id);

            if (course != null)
            {                    
                var countAlreadyAppliedThisCourseBefore =
                    course.OnlineCourseSubscriptions.Count(x => x.StudentId == user.UserId);
                if (countAlreadyAppliedThisCourseBefore > 0)
                {
                    ViewBag.AlreadyApplied = "Yes";
                }
                if (course.IsPublishable == false)
                {
                    if (user != null && course.TeacherId == user.UserId)
                    {
                        model.Course = course;
                        model.Batches = batches;
                    }
                }
                else
                {
                    model.Course = course;
                    model.Batches = batches;
                }
            }
        return View(model);
    }


    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            _db.Dispose();
        }
        base.Dispose(disposing);
    }

我总是得到一个与连接有关的错误。我首先使用Azure Sql数据库与实体框架代码和我的互联网连接工作没有任何下降,但我的应用程序在很大程度上依赖于数据库。想知道我在做错我的代码或数据库连接的方式吗?有什么步骤可以纠正这个问题吗?当我在Entity框架之前使用正常的sql数据库连接时,我从未遇到过这样的问题。任何帮助表示赞赏。

0 个答案:

没有答案