继承自实体框架代码中的DbSet <tentity> </tentity>

时间:2015-02-26 16:40:34

标签: c# entity-framework

我想问一下,是否可以创建继承自DbSet的classCollection并在DbContext中使用此集合。我使用Entity framework - Code first。

我有简单的班级学生:

public class Student
{
    public int StudentId { get; set; }
    public string Name { get; set; }
}

然后我尝试创建自定义StudentCollection,我可以在其中定义自定义方法:

public class StudentCollection : DbSet<Student>
{
    public void CustomAdd(Student student) { /*...*/ }
    public bool Exists(Student student) { return true; }

}

最后我想根据数据库中的EF创建表使用StudentCollection。

public class ModelContext : DbContext
{
  //typical use: Works ok
  public virtual DbSet<Student> Students { get; set; }

  //Dreamed use: Generate error, EntityType 'StudentCollection' has no key defined.
  public virtual StudentCollection ExtendedStudents { get; set; }
}

最后我想写一下:

Db.ExtendedStudents.CustomAdd(newStudent);

感谢您的帮助。

0 个答案:

没有答案