如何连接多个表?
Posted
技术标签:
【中文标题】如何连接多个表?【英文标题】:How to join multiple tables? 【发布时间】:2012-06-27 14:18:00 【问题描述】:我有以下课程。我有一个描述类的对象var
。我想使用 Linq to Sql 或 Lambda 表达式选择与 var
对象中提供的客户端相关的余额。如何连接这些表以从 Account 表中获取余额?
public class Description
public int DescriptionID get; set;
// Attributes
public int ClientID get; set;
[ForeignKey("ClientID")]
public virtual Client Client get; set;
public class Client
public int ClientID get; set;
// Attributes
public int UserID get; set;
[ForeignKey("UserID")]
public virtual User User get; set;
public class User
public int UserID get; set;
// Attributes
public class Account
public int AccountID get; set;
[Required, Column("Balance"), Display(Name = "Account Balance")]
public double Balance get; set;
public int UserID get; set;
[ForeignKey("UserID")]
public virtual User User get; set;
【问题讨论】:
***.com/questions/21051612/… 这能回答你的问题吗? Entity Framework Join 3 Tables 【参考方案1】:你可以试试这个:
var balance = (from a in context.Accounts
join c in context.Clients on a.UserID equals c.UserID
where c.ClientID == yourDescriptionObject.ClientID
select a.Balance)
.SingleOrDefault();
或者 - 如果你只有 DescriptionID
:
var balance = (from a in context.Accounts
join c in context.Clients on a.UserID equals c.UserID
join d in context.Descriptions on c.ClientID equals d.ClientID
where d.DescriptionID == yourDescriptionID
select a.Balance)
.SingleOrDefault();
(或FirstOrDefault()
或ToList()
或Sum()
?因为您的模型将允许客户/描述与多个帐户相关...)
【讨论】:
以上是关于如何连接多个表?的主要内容,如果未能解决你的问题,请参考以下文章