【问题标题】:Entity Framework as UnitOfWork/Repository?实体框架作为 UnitOfWork/Repository?
【发布时间】:2012-09-18 18:38:07
【问题描述】:

我正在学习 Entity Framework/MVC 4,并开始学习一些关于创建存储库和抽象 EF 的教程。

我注意到的是,EF 似乎已经是 UnitOfWork/Repository 模式。

我尝试使用 DbSet<TEntity> 作为基类创建自定义 DbSet,但由于以下异常而无法使其工作:The type 'System.Data.Entity.DbSet<TEntity>' has no constructors defined

这是我正在尝试做的事情:

public class RolesDbSet : DbSet<Role>
{
    public bool IsNameInUse(string name, int id = 0)
    {
        if (id == 0)
            return this.Any(r => r.Name == name);
        return this.Any(r => r.Name == name && r.ID != id);
    }
}

public class MyEntities : DbContext
{
    public MyEntities() : base("MyEntities")
    {
        Database.SetInitializer(new MyDevelopmentInitializer());
    }       

    public RolesDbSet Roles { get; set; }
    public DbSet<User> Users { get; set; }
    public DbSet<Password> Passwords { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new UserConfiguration());
        base.OnModelCreating(modelBuilder);
    }
}

那我就可以这样做了:

bool inUse;
using (var db = new MyEntities())
{
    inUse = db.Roles.IsNameInUse("Employee");
}

有没有办法做到这一点?

【问题讨论】:

    标签: asp.net-mvc entity-framework unit-of-work


    【解决方案1】:

    是的EF already implements repository and unit of work patterns

    您不能创建派生的DbSet&lt;T&gt;,因为它没有公共或受保护的构造函数。唯一的方法是直接实现IDbSet&lt;T&gt;,这太复杂了。但是你可以用同样的方式使用扩展方法而不是使用实例方法,它就可以工作:

    public static class RoleExtensions 
    {
        public static bool IsNameInUse(this IQueryable<Role> query, string name, int id = 0)
        {
            if (id == 0)
                return query.Any(r => r.Name == name);
            return query.Any(r => r.Name == name && r.ID != id);
        }
    }
    

    【讨论】:

    • 使用扩展方法的好主意!我几乎将它们用于其他所有事情,不知道为什么我没有想到在这里使用它们。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-08
    • 2012-07-21
    相关资源
    最近更新 更多