1

我正在尝试为任何数据提供者/orm 制作一个具有通用存储库的通用 3 层应用程序。我只是重写了代码,并在尝试在 DbSet 中执行操作时遇到了对象引用未设置为对象实例的错误。我完全糊涂了……至少把我推向正确的方向。

存储库.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();
    }
}

应用上下文.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();
}

配置.cs

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

    protected override void Seed(AppContext context)
    {

    }
}
4

1 回答 1

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;
于 2013-05-09T19:19:49.113 回答