ASP.NET MVC-使用LINQ连接表
我的应用程序结构如下:ASP.NET MVC-使用LINQ连接表,linq,linq-to-sql,Linq,Linq To Sql,我的应用程序结构如下: namespace DomainModel.Abstract { public interface IContentItemsRepository { IQueryable<Content> ContentItems { get; } IQueryable<Category> Categories { get; } IQueryable<ContentCategory>
namespace DomainModel.Abstract
{
public interface IContentItemsRepository
{
IQueryable<Content> ContentItems { get; }
IQueryable<Category> Categories { get; }
IQueryable<ContentCategory> ContentCategories { get; }
}
}
namespace DomainModel.Entities
{
[Table(Name = "Content")]
public class Content
{
[Column(IsPrimaryKey = true,
IsDbGenerated = true,
AutoSync = AutoSync.OnInsert)]
public int content_id { get; set; }
[Column]
public string type { get; set; } // article, video, recipe, tool
[Column]
public string title { get; set; }
...
namespace DomainModel.Entities
{
[Table(Name = "Content_Categories")]
public class ContentCategory
{
[Column(IsPrimaryKey = true,
IsDbGenerated = true,
AutoSync = AutoSync.OnInsert)]
public int content_category_id { get; set; }
[Column]
public int content_id { get; set; }
[Column]
public int category_id { get; set; }
...
namespace DomainModel.Entities
{
[Table(Name = "Categories")]
public class Category
{
[Column(IsPrimaryKey = true,
IsDbGenerated = true,
AutoSync = AutoSync.OnInsert)]
public int category_id { get; set; }
[Column]
public string category_name { get; set; }
[Column]
public string type { get; set; } //recipe,tool,other
[Column]
public int ordering { get; set; }
...
并获取文章列表。没问题
但是,我现在需要根据类别选择内容。所以,我需要将内容连接到ContentCategory,再连接到Category
我不知道怎么做。任何帮助都将不胜感激
谢谢
编辑:
我想我的部分问题是我甚至不知道如何称呼我正在做的事情,所以很难找到这个。我是在对SQL执行LINQ,还是对实体执行LINQ,还是对对象执行LINQ?您正在寻找的概念称为LINQ中的SelectMany,有很多方法可以实现它 一是:
var content =
from category in _categoryRepository.CategoryItems
join contCat in _contentCategoryRepository.Items
on category.category_id == conCat.category_id
where category.category_id == parameter
select contCat.content_id;
从这里,您应该能够扩展它,以提取所有需要的数据…查看
into
关键字,如果您还没有查看过,请查看。连接查询将是这样的
var content=
from category in _contentRepository.Category
join contentCategory in _contentRepository.ContentCategory
on category.category_id equals contentCategory.category_id
join content in _contentRepository.Content
on content.content_id equals contentCategory.content_id
where category.category_id==@yourcategoryId
select new {type , title }
这不是一个真正的mvc问题。您还应该添加一个linq to sql标记。当您连接两个表时,是否需要指定某个连接列?我在第二个“连接”和“位置”上收到一个错误,上面写着:预期上下文关键字“等于”。对不起,编辑了我的查询,连接应在外键上使用等于。
var content=
from category in _contentRepository.Category
join contentCategory in _contentRepository.ContentCategory
on category.category_id equals contentCategory.category_id
join content in _contentRepository.Content
on content.content_id equals contentCategory.content_id
where category.category_id==@yourcategoryId
select new {type , title }