通用扩展-服务未实现接口成员

时间:2019-04-20 09:32:24

标签: c# .net-core entity-framework-core

有人可以帮我弄清楚我在哪里出问题了。

我正在尝试为.Net Core中的服务实现通用扩展方法。

这是我的界面-

public interface IContactService : IAddable<Contact>
{
    Task<List<Contact>> GetAll();
}

我的模特-

public partial class Contact : IBaseEntity
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public string Phone { get; set; }
}

模型的接口-

public interface IBaseEntity { }

然后我有我的通用扩展名-

public interface IAddable<T>
{
    AppContext Context { get; }
}

public static class IAddableExentions
{
    public static async Task<T> Add<T>(this IAddable<T> addable, T entity) where T : class, IBaseEntity
    {
        await addable.Context.Set<T>().AddAsync(entity);
        await addable.Context.SaveChangesAsync();

        return entity;
    }
}

我的服务-

public class ContactService : IContactService
{
    public AppContext Context;

    public ContactService(AppContext context)
    {
        Context = context;
    }

    public async Task<List<Contact>> GetAll()
    {
        var contacts = await Context
            .Contacts
            .ToListAsync();

        return contacts;
    }
}

现在,编译器在抱怨-

  

“ ContactService”未实现接口成员   “ IAddable.Context”

当我尝试致电service.Add(contact)时,我得到-

  

IContactService不包含“添加”和“否”的定义   接受类型的第一个参数的可访问扩展方法   可以找到IContactService。

我已经在另一个项目中工作了,但是对于我一生来说,我不知道为什么它在这里不起作用...

1 个答案:

答案 0 :(得分:1)

您已将Context声明为ContactService的字段,

public class ContactService : IContactService
{
    public AppContext Context; //<-- field

//...

但使用IAddable<T>界面

public interface IAddable<T>
{
    AppContext Context { get; }
}
源自IContactService

指出它(Context)应该是一个属性:

public class ContactService : IContactService
{
    public AppContext Context { get; }

//...