简体   繁体   English

通用存储库不允许我添加方法

[英]generic repository doesn't let me add methods

I'm building an ASP.NET Core web application.我正在构建一个 ASP.NET 核心 web 应用程序。 The controller use a generic repository within methods like "Get, GetById, Post, Update ecc.". controller 在“Get、GetById、Post、Update ecc.”等方法中使用通用存储库。 When i use these methods in the controller and I try to add methods like "Include, Where ecc."当我在 controller 中使用这些方法时,我尝试添加诸如“包含,在哪里 ecc”之类的方法。 pops this error: CS1501:弹出此错误:CS1501:

"No overload for method 'method' takes 'number' arguments" “方法'方法'没有重载需要'数字'参数”

var license = await _repo.GetSingleById(id).Include("product");

i tried to return also IQueryable but it gaves me the same error.我也尝试返回 IQueryable 但它给了我同样的错误。

GetSingleById is almost certainly returning a single item, and that means you're already past the point where you are able to use Include since the query has already been executed. GetSingleById几乎可以肯定返回单个项目,这意味着您已经过了可以使用Include的点,因为查询已经执行。 So your simplest option is to pass in the Include expressions whenever you need them.因此,您最简单的选择是在需要时传入Include表达式。 First let's assume you have an existing function that looks like this:首先,假设您有一个现有的 function,如下所示:

public async T GetSingleById(int id)
{
    return _context.Set<T>()
        .Single(e => e.Id == id);
}

You would need to change it to something like this instead:您需要将其更改为以下内容:

public async T GetSingleById(int id, params Expression<Func<T, object>>[] includes)
{
    IQueryable<T> query = _context.Set<T>();

    if(includes != null && includes.Any())
    {
        foreach(var include in includes)
        {
            query = query.Include(include);
        }
    }

    return query.Single(e => e.Id == id);
}

Now you can call it like this:现在你可以这样称呼它:

// As before without any includes
var license = await _repo.GetSingleById(id);

// A single include
var license = await _repo.GetSingleById(
    id, 
    e => e.Product);

// Multiple includes
var license = await _repo.GetSingleById(
    id, 
    e => e.Product, 
    e => e.SomethingElse);

Note that I have specifically used the lambda syntax for includes rather than the string overload.请注意,我专门将 lambda 语法用于包含而不是字符串重载。 These are much safer to use since they give you compile-time checking.这些使用起来更安全,因为它们为您提供编译时检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM