C# - 无法将实体接口强制转换为实体

时间:2017-05-15 19:45:24

标签: c# entity-framework interface

我有以下代码:

public class CoursesController : ApiController
{
    private ITanulmanyokEntities _entities;

    public CoursesController()
        : this(new TanulmanyokEntities()) // ERROR HERE
    {
    }
    public CoursesController(ITanulmanyokEntities entities)
    {
        if (entities == null)
            throw new ArgumentNullException("entities");

        _entities = entities;
    }

}

在这里,我创建了一个界面:

public interface ITanulmanyokEntities : IDisposable
{
    Int32 SaveChanges();

    DbSet<Application> Applications { get; set; }
    DbSet<Course> Courses { get; set; }
    DbSet<EducationSubject> EducationSubjects { get; set; }
    DbSet<EducationUser> EducationUsers { get; set; }
    DbSet<Program> Programs { get; set; }

}

这应该是从数据库生成的实体的接口:

public partial class TanulmanyokEntities : DbContext
{
    public TanulmanyokEntities()
        : base("name=TanulmanyokEntities")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }

    public virtual DbSet<Application> Applications { get; set; }
    public virtual DbSet<Course> Courses { get; set; }
    public virtual DbSet<EducationSubject> EducationSubjects { get; set; }
    public virtual DbSet<EducationUser> EducationUsers { get; set; }
    public virtual DbSet<Program> Programs { get; set; }
}

然而,我似乎无法将一个转换为另一个。请参阅注释行。问题是,我的编译器无法转换接口/真实的东西。我想我实现了所有必须实现的东西(我也遵循一些有效的示例代码)。我错过了什么?

2 个答案:

答案 0 :(得分:0)

您需要声明TanulmanyokEntities实施ITanulmanyokEntities

public partial class TanulmanyokEntities:DbContext,ITanulmanyokEntities

答案 1 :(得分:0)

解决方案是创建另一个部分类:

public partial class TanulmanyokEntities : ITanulmanyokEntities
{
}

这样,我就不必弄乱生成的代码了。