我有以下课程。我有一个Description类的对象var
。我想使用Linq to Sql或Lambda表达式选择与var
对象中提供的客户端相关的余额。如何连接这些表以从帐户表中获取余额?
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; }
}
答案 0 :(得分:11)
你可以试试这个:
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()
?因为您的模型会允许客户/说明与多个帐户相关...)