如何使用具有泛型类型</t>的DbSet <t>

时间:2014-05-04 04:53:12

标签: c# generics interface generic-programming dbset

我有一个界面:

public interface ILanguageEntity
{
    int Id { get; set; }

    string Name { get; set; }

    string Code { get; set; }

    string Culture { get; set; }

    string LocalName { get; set; }

    bool IsRightToLeft { get; set; }
}

我已经将其实现为像这样的实体:

public class LanguageEntity : ILanguageEntity
{
    public int Id { get; set; }

    public string Name { get; set; }

    public string Code { get; set; }

    public string Culture { get; set; }

    public string LocalName { get; set; }

    public bool IsRightToLeft { get; set; }
}

在我的服务中,我希望为这个实体提供一个属性,它返回它的DbSet:

public class LanguageService : ILanguageService
{
    public ApplicationContext Context { get; set; }

    public DbSet<ILanguageEntity> DbSet { get { return Context.Set<LanguageEntity>(); } }

}

但这是不可能的,因为我正在返回DbSet<LanguageEntity>类型,而我必须返回DbSet<ILanguageEntity>类型,正如编译器所说。我该怎么办?

1 个答案:

答案 0 :(得分:0)

我认为ApplicationContext至少应该有一个ILanguageEntity DbSet

以下是我的想法:

public class LanguageService : ILanguageService
{
    public ApplicationContext Context { get; set; }

    public DbSet<ILanguageEntity> DbSet
    {
        get
        {
            return Context.LanguageEntities;
        }
        set
        {
            throw new NotImplementedException();
        }
    }
}

public class ApplicationContext : DbContext
{
    public DbSet<ILanguageEntity> LanguageEntities { get; set; }
}

public interface ILanguageService
{
    DbSet<ILanguageEntity> DbSet { get; set; }
}