如何连接多个表? [英] How to join multiple tables?

查看:25
本文介绍了如何连接多个表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程.我有一个 Description 类的对象 var.我想使用 Linq to Sql 或 Lambda 表达式选择与 var 对象中提供的 Client 相关的 Balance.如何连接这些表以从 Account 表中获取余额?

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:

Or - if you only have the 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆