我有以下类(class)。我有一个Description类的对象var。我想使用Linq to Sql或Lambda表达式选择与var对象中提供的Client相关的Balance。如何联接这些表以从“帐户”表中获取余额?

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()?因为您的模型允许客户/描述与多个帐户相关...)

关于entity-framework - 如何联接多个表?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11204367/

10-11 18:17