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?