Die*_*_DX 6 c# entity-framework asp.net-mvc-3
所以我试图为 where 查询创建一个通用函数,而不是使用存储库,所以可以做这样的事情吗?
public IEnumerable<T> Something<T>(int authorId) where T : class
{
return Vmsb.Set<T>().Where(c => c.AuthorId== authorId);
}
Run Code Online (Sandbox Code Playgroud)
现在我不能,因为它不知道 c.AuthorId 是什么
创建一个接口IHaveAuthor并在具有此属性的部分类上指定它:
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
{
}
Run Code Online (Sandbox Code Playgroud)
然后将接口指向泛型类型where约束下:
public IEnumerable<T> GetAuthorPublicationsOf<T>(int authorId)
where T : class, IHaveAuthor
{
return Vmsb.Set<T>().Where(c => c.AuthorId == authorId);
}
Run Code Online (Sandbox Code Playgroud)
以及用法:
var authorBooks = query.GetAuthorPublicationsOf<Book>(authorId);
var authorArticles = query.GetAuthorPublicationsOf<Article>(authorId);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2993 次 |
| 最近记录: |