通用的DbContext的查询在哪里 [英] Generic DBContext for Where Query

查看:88
本文介绍了通用的DbContext的查询在哪里的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想做一个泛型函数用于查询的地方,不使用存储库
这样就可以做这样的事情?

so I am trying to make a generic function for a where query, not using repository so it is possible to do something like this?

   public IEnumerable<T> Something<T>(int authorId) where T : class
    {
        return Vmsb.Set<T>().Where(c => c.AuthorId== authorId);

    }

现在我不能,因为它不知道c.AuthorId是

now I can't because it dont know what c.AuthorId is

推荐答案

创建一个接口 IHaveAuthor ,并指定在部分类与此属性:

Create an interface IHaveAuthor and specify it on partial classes with this property:

public interface IHaveAuthor
{
    int AuthorId { get; set; }
}

//Note that the interface is already implemented in auto-generated part.
//Or if it's Code First, just specify it directly on your classes.
public partial class Book : IHaveAuthor
{
}

public partial class Article : IHaveAuthor
{
}

然后,接口点泛型类型 其中在 约束:

public IEnumerable<T> GetAuthorPublicationsOf<T>(int authorId) 
    where T : class, IHaveAuthor
{
    return Vmsb.Set<T>().Where(c => c.AuthorId == authorId);
}

和用法:

var authorBooks = query.GetAuthorPublicationsOf<Book>(authorId);
var authorArticles = query.GetAuthorPublicationsOf<Article>(authorId);

这篇关于通用的DbContext的查询在哪里的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆