c# - 使用 Linq 从两个表中获取数据

标签 c# asp.net linq entity-framework

首先我想说我对 Entity Framework 是全新的,但我想学习它所以我的问题是我有三个表。 第一个用于存储作者详细信息。
表的结构是

enter image description here

存储所有文章的第二张表
表的结构是

enter image description here

和存储评论的表3
表的结构是

enter image description here

正如我的客户所希望的那样,我在数据库中没有外键,但它们之间存在关系,我正在通过代码处理它们(请不要问为什么,因为我也不知道为什么我的客户不想要外键) :)

我在做什么 现在我有一个管理面板,其中有一个 GridView ,我在其中绑定(bind)作者表,单击任何行都会打开另一个页面

页面源代码示例:

<div>
 <asp:ListView ID="articles" runat="server">
<ItemTemplate>
Label1//Here Goes the Article Id
Label2//Here Goes the Article Names
<div>
//Another Listview For Comments
 <asp:ListView ID="comments" runat="server">
<ItemTemplate>
Here Goes All the Comments
</ItemTemplate>
</asp:ListView>
</div>
</ItemTemplate>
</asp:ListView>

所以我在做什么首先我绑定(bind)文章列表并在绑定(bind)之后 我正在文章列表中执行 Foreach 循环以查找所有文章 ID 和评论 ListView 注:至于代码大家可以看到评论列表会针对每篇文章重复 找到评论 ID 后,我会获取该 ID 的评论并将其绑定(bind)到评论列表。

所以我的问题是我连接到数据库两次,但我想在单次连接中执行此操作,有什么方法可以在获取文章时获取文章 ID 的评论表的所有行.

我的文章获取代码是

Context.Artcles.Select(x=>x.x.RefAuth==AuthId).ToList();

我将从 GridView Row Click 获取 AuthID。

我知道这不是什么大事,但我对此完全陌生。

问题:2

感谢Ehsan Sajjad给了我完美的解决方案所以还有另一个问题。在我的第一个问题中,我从两个表中获取数据,所以建议是在 Linq 中使用 Join,但在我的第二个问题中,我有一个表,表格式是这样的。
enter image description here
如果类型为 1 则接收,否则如果类型为 2 则回复。
Refmailid 是我回复邮件的时间,如果“mailid”为 1,那么对于该回复,“refmailid”将为 1,通过它我可以获取一封邮件的所有回复 所以我想要的,就像这里的文章和评论一样,我也正在从用户那里获取所有收到的邮件,其中 from Column 是一个 Unique Userid

所以我什么时候去取

Context.SupportRequests.Select(x=>x.from=="theuniqueuserid" && type==1).ToList();

我将从该用途中获取所有收到的邮件,就像之前的 div 一样

<div>
     <asp:ListView ID="receivedmails" runat="server">
    <ItemTemplate>
    Label1//Here Goes subject
    Label2//Here Goes the content
    <div>
    //Another Listview For Replies
     <asp:ListView ID="replies" runat="server">
    <ItemTemplate>Here Goes All the replies will be more then one so it will be reapeated
with 
//Subject
//Content
    </ItemTemplate>
    </asp:ListView>
    </div>
    </ItemTemplate>
    </asp:ListView>
</div>

那么我在做什么?首先我绑定(bind)接收列表并在绑定(bind)之后 我正在接收列表中执行 Foreach 循环以查找所有“mailid”和回复的 ListView 注意:至于代码您可以看到回复列表将针对每封收到的邮件重复 找到“mailid”后,我将获取该 id 的回复并将其绑定(bind)到回复列表。 代码

 Context.SupportRequests.Select(x=>x.refmailid=="mailid").ToList();

最佳答案

你需要加入

var result = (from a in Context.Articles
             join c in Context.Comments on a.ArticleId equals c.ArticleId
             select new{ Article = a, Comment = c});

关于c# - 使用 Linq 从两个表中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28587278/

相关文章:

javascript - 如何在 IE8 及以上版本中使用 History.back()

asp.net - reCaptcha 验证超时异常

c# - 无法在 LinQ 查询中将类型 'bool?' 隐式转换为 'bool'?

c# - 如何检查 C# 中的两个值是否相等? (给定任何类型的值)

c# - LINQ 中的 "RemoveAll"怎么可能比迭代快得多?

jquery - 切换开关在 PartialView 中不起作用

c# - 如何根据另一个列表中一个属性的所有值过滤 linq 查询

c# - Where() with Replace() in Dictionary.Where(p => p.Key is T)

c# - Xamarin - PopAsync() 后刷新列表

c# - 如何使任务栏缩略图上的区域在 Windows 7 中显示为透明?