Code First Generic Repository with existing Databa

2019-08-29 10:56发布

I have a Generic Repository class using code first to perform data operations.

public class GenericRepository<T> where T : class
{

public DbContext _context = new DbContext("name=con");

private DbSet<T> _dbset;

public DbSet<T> Dbset
{

    set { _dbset = value; }
    get
    {
        _dbset = _context.Set<T>();
        return _dbset;
    }

}

public IQueryable<T> GetAll()
{
    return Dbset;
}

} 

I have an entity class Teacher, which maps to an existing table "Teacher" in my database, with exactly the same fields.

public class Teacher
{
public Teacher()
{
    //
    // TODO: Add constructor logic here
    //
}

public int TeacherID { get; set; }

public string FirstName { get; set; }

public string LastName { get; set; }

public int Age { get; set; }
}

I have the following code below which binds data from Teacher to a repeater control.

 GenericRepository<Teacher> studentrepository = new GenericRepository<Teacher>();
    rptSchoolData.DataSource = studentrepository.GetAll().ToList();
    rptSchoolData.DataBind();

But I get an exception exception "The entity type Teacher is not part of the model in the current context". Do I have to do any additional work when using an existing database for code first?

1条回答
成全新的幸福
2楼-- · 2019-08-29 11:30

You must create a context class that derives from DbContext. The class should have properties of type DbSet<T> which will give EF enough information to create and communicate with a database with default naming and association conventions. It will use properties like Student.Teacher (if any) to infer foreign key associations:

public class MyContext: DbContext
{
    public DbSet<Teacher> Teachers { get; set; }
    public DbSet<Student> Students { get; set; }
    ...
}

If the defaults are not what you want, or when you've got an existing database that you want to match with the names and associations in your model you can do two (or three) things:

  • Override OnModelCreating to configure the mappings manually. Like when the tables in the database have those ugly prefixes (to remind people that they see a table when they see a table):
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Teacher>()
                    .Map(e => e.ToTable("tblTeacher"));
        ...
    }
  • (Less favorable) Use data annotations to do the same.
  • Turn it around and use Entity Framework Powertools to reverse-engineer a database into a class model including fluent mappings and a DbContext-derived context. Maybe easier to modify an existing model than to start from scratch.
查看更多
登录 后发表回答