10

我有以下课程。我有一个var描述类的对象。我想var使用 Linq to Sql 或 Lambda 表达式选择与对象中提供的客户端相关的余额。如何加入这些表以从 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; }

    }
4

1 回答 1

19

你可以试试这个:

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

于 2012-06-26T11:54:35.537 回答