如何联接多个表? [英] How to join multiple tables?
本文介绍了如何联接多个表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下课程.我有一个Description类的对象var
.我想使用Linq to Sql或Lambda表达式选择与var
对象中提供的Client相关的Balance.如何联接这些表以从帐户"表中获取余额?
I have the following classes. I have a object var
of Description class. I want to select Balance related to the Client provided in the var
object using Linq to Sql or Lambda expression. How to join these tables to get the Balance from Account table?
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; }
}
推荐答案
您可以尝试以下方法:
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()
?因为您的模型允许客户/描述与多个帐户相关...)
(Or FirstOrDefault()
or ToList()
or Sum()
? Because your model would allow that clients/descriptions are related to multiple accounts ...)
这篇关于如何联接多个表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文