从多对多关系中检索对象
Retrieve objects from many to many relationship
我正在使用 Entity Framework Code First,我的模型中有以下对象:
public class Category {
[DatabaseGenerated( DatabaseGeneratedOption.Identity ), Key]
public int CategoryId { get; set; }
[Required, MaxLength( 128 ), Index( IsUnique = true)]
public string CategoryName { get; set; }
public string Description { get; set; }
public virtual ICollection<Article> Articles { get; set; }
}
public class Article {
[DatabaseGenerated( DatabaseGeneratedOption.Identity ), Key]
public int ArticleId { get; set; }
[Required, MaxLength( 128 ), Index]
public string ArticleName { get; set; }
public string Description { get; set; }
public virtual ICollection<Category> Categories { get; set; }
}
我正在我的数据访问层中实现一种方法来检索所选 Categories
:
之一中的所有 Articles
IEnumerable<Article> GetArticles( int[] categoryIds );
我的问题:如何构建查询表达式?如果我在 SQL 中执行此操作,我会编写如下查询:
SELECT a.*
FROM Articles a
JOIN ArticlesInCategories AS aic ON a.ArticleId = aic.ArticleId
JOIN Categories AS c on aic.CategoryId = c.CategoryId
WHERE c.CategoryId IN ( . . . )
那是否意味着我会这样写?
return ( from a in context.Articles
join c in context.Categories ON a.CategoryId = c.CatgegoryId
where categoryIds.Contains( c.CategoryId ) );
唯一的问题是 Article
class 没有 CategoryId
属性.
如何构建此查询?
您需要反转查询并使用 SelectMany()
:
return ( from c in context.Categories
where categoryIds.Contains( c.CategoryId ) )
.SelectMany(category => category.Arcticles);
我正在使用 Entity Framework Code First,我的模型中有以下对象:
public class Category {
[DatabaseGenerated( DatabaseGeneratedOption.Identity ), Key]
public int CategoryId { get; set; }
[Required, MaxLength( 128 ), Index( IsUnique = true)]
public string CategoryName { get; set; }
public string Description { get; set; }
public virtual ICollection<Article> Articles { get; set; }
}
public class Article {
[DatabaseGenerated( DatabaseGeneratedOption.Identity ), Key]
public int ArticleId { get; set; }
[Required, MaxLength( 128 ), Index]
public string ArticleName { get; set; }
public string Description { get; set; }
public virtual ICollection<Category> Categories { get; set; }
}
我正在我的数据访问层中实现一种方法来检索所选 Categories
:
Articles
IEnumerable<Article> GetArticles( int[] categoryIds );
我的问题:如何构建查询表达式?如果我在 SQL 中执行此操作,我会编写如下查询:
SELECT a.*
FROM Articles a
JOIN ArticlesInCategories AS aic ON a.ArticleId = aic.ArticleId
JOIN Categories AS c on aic.CategoryId = c.CategoryId
WHERE c.CategoryId IN ( . . . )
那是否意味着我会这样写?
return ( from a in context.Articles
join c in context.Categories ON a.CategoryId = c.CatgegoryId
where categoryIds.Contains( c.CategoryId ) );
唯一的问题是 Article
class 没有 CategoryId
属性.
如何构建此查询?
您需要反转查询并使用 SelectMany()
:
return ( from c in context.Categories
where categoryIds.Contains( c.CategoryId ) )
.SelectMany(category => category.Arcticles);