DbSet对象引用未设置为对象的实例

时间:2013-05-09 15:31:06

标签: c# entity-framework generics data-access-layer 3-tier

我正在尝试为任何数据提供者/ orm创建具有通用存储库的通用3层应用程序。我只是重写了代码并且在DbSet中尝试make动作时,陷入了对象引用的错误而没有设置为对象的实例。我完全糊涂了......至少让我朝着正确的方向努力。

Repository.cs

 public class Repository<T> : IRepository<T> where T : class
{

    public IUnitOfWork UnitOfWork { get; set; }
    private IDbSet<T> _objectset;

    private IDbSet<T> DbSet
    {
        get { return _objectset ?? (_objectset = UnitOfWork.Context.Set<T>()); }
    }
public List<T> GetAll()
    {
        try
        {
            return DbSet.ToList();
        }
        catch (Exception)
        {
            throw new Exception("Error in repository while attempts get all elements");
        }
    }
}

EFUnitOfWork.cs

 public class EfUnitOfWork : IUnitOfWork
{
    public EfUnitOfWork()
    {
        Context = new AppContext();
    }

    public DbContext Context { get; set; }

    public void Commit()
    {
        Context.SaveChanges();
    }

    public bool LazyLoadingEnabled
    {
        get { return Context.Configuration.LazyLoadingEnabled; }
        set { Context.Configuration.LazyLoadingEnabled = value; }
    }

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

AppContext.cs

 public class AppContext : DbContext, IDbContext
{
    public AppContext()
    {
        Database.SetInitializer(new MigrateDatabaseToLatestVersion<AppContext,            Configuration>());
        Configuration.ProxyCreationEnabled = false;
    }

    public DbSet<Logic> Logics { get; set; }

    public DbSet<Category> Categories { get; set; }

    public new IDbSet<TEntity> Set<TEntity>() where TEntity : class
    {
        return base.Set<TEntity>();
    }
}

IDbContext.cs

public interface IDbContext
{
    IDbSet<TEntity> Set<TEntity>() where TEntity : class;
    int SaveChanges();
    void Dispose();
}

Configuration.cs

class Configuration : DbMigrationsConfiguration<AppContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = true;
        AutomaticMigrationDataLossAllowed = true;
    }

    protected override void Seed(AppContext context)
    {

    }
}

1 个答案:

答案 0 :(得分:1)

我建议你在构造函数中将Repository更改为期望IUnitOfWork,因为没有它就无效。

public class Repository<T> : IRepository<T> where T : class
{
    private readonly IUnitOfWork _unitOfWork;
    public Repository(IUnitOfWork unitOfWork;)
    {
        _unitOfWork = unitOfWork;
    }
    public IUnitOfWork UnitOfWork { get { return _unitOfWork; } }
}

IDbContext应定义为实现IDisposable(并从接口定义中删除Dispose方法)

public interface IDbContext : IDisposable
{
    IDbSet<TEntity> Set<TEntity>() where TEntity : class;
    int SaveChanges();
}

来自AppContext的以下代码行将具有禁用延迟加载的效果,因为代理实现了延迟加载

Configuration.ProxyCreationEnabled = false;