【问题标题】:Generic Extension - Service does not implement interface member [duplicate]通用扩展 - 服务未实现接口成员 [重复]
【发布时间】:2019-04-20 09:32:23
【问题描述】:

有人可以帮我弄清楚我哪里出错了。

我正在尝试为 .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 不包含 Add 和 no 接受类型的第一个参数的可访问扩展方法 可以找到 IContactService。

我已经在另一个项目中使用了它,但是对于我的生活,我无法弄清楚为什么它在这里不起作用...

【问题讨论】:

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


    【解决方案1】:

    您将Context 声明为ContactService 的字段,

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

    但是IAddable&lt;T&gt;接口

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

    其中IContactService 派生自,指示它 (Context) 应该是一个属性:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-04
      • 1970-01-01
      • 1970-01-01
      • 2013-12-27
      • 1970-01-01
      • 2023-02-15
      • 1970-01-01
      相关资源
      最近更新 更多