0

I'm in the process of learning Entity Framework/MVC 4, and started following some tutorials on creating Repositories and abstracting away EF.

What I've noticed is that EF seems to already be a UnitOfWork/Repository pattern.

I tried creating custom DbSets by using DbSet<TEntity> as a base class, but couldn't get it to work because of the following exception: The type 'System.Data.Entity.DbSet<TEntity>' has no constructors defined.

Here's what I'm attempting to do:

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

Then I would be able do do this:

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

Is there a way to accomplish this?

Sam
  • 9,933
  • 12
  • 68
  • 104

1 Answers1

2

Yes EF already implements repository and unit of work patterns.

You cannot create derived DbSet<T> because it doesn't have public nor protected constructor. The only way is to implement IDbSet<T> directly and that is too complex. But instead of using instance methods you can in the same way use extension methods and it will just work:

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);
    }
}
Community
  • 1
  • 1
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • Great idea on using Extension methods! I use them for almost everything else, not sure why I didn't think of using them here. – Sam Sep 18 '12 at 18:48