【问题标题】:Trying to get list of Id's from list of objects in MVC controller试图从 MVC 控制器中的对象列表中获取 Id 列表
【发布时间】:2019-09-17 02:25:33
【问题描述】:

我正在根据用户所在的“家庭”设置所有银行账户及其相应交易的列表,以供用户查看。我可以很好地获取账户列表,但无法获取交易。

var model = new DashboardViewModel();
var user = db.Users.Find(User.Identity.GetUserId());

var houseAccounts = db.BankAccounts.Where
    (b => b.HouseholdId == user.MyHouseId).ToList();

model.BankAccounts = houseAccounts;

model.Transactions = db.Transactions.Where
    (t => t.BankAccountsId == houseAccounts.Id);

houseAccounts.Id,我收到一条错误消息,指出“列表不包含 'Id' 的定义...”

为每个 BankAccount 分配一个 HouseholdId,并为每个 Transaction 分配一个 BankAccountsId。我的数据库中的所有对象都有一个由我构建的类创建的 ID 号。我怎样才能把它弄到这里来?

【问题讨论】:

    标签: c# linq model-view-controller


    【解决方案1】:

    在 houseAccounts.Id,我收到一条错误消息,指出“列表不包含 'Id' 的定义...”

    houseAccounts 是一个 BankAccounts 列表,而 List 没有 ID。 实际上 List 中的每个对象(本例中为 BankAccout)都有一个 Id。

    因此,如果您想要来自 houseAccounts 的 id,您可以执行以下操作:

    var houseAccountIdList = houseAccounts.Select(it => it.Id);
    

    有了Id List,你可以得到这样的交易:

    model.Transactions = db.Transactions.Where(it => houseAccountIdList.contains(it.BankAccountsId));
    

    【讨论】:

      【解决方案2】:

      houseAccounts 类型是 BankAccount 的列表,除非您引用列表中的项目,否则您绝对无法从中获取属性 Id。试试下面:

       foreach (var account in houseAccounts){
          //Retrieve and add transactions based on each individual list-item id
        model.Transactions.Add(db.Transactions.Where (t => t.BankAccountsId == account.Id));
        }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-09-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-30
        相关资源
        最近更新 更多