1

我一般从 asp.net mvc3 和 mvc 开始,同时我也在学习实体框架。

我正在构建的应用程序允许用户为其他用户创建账单或付款,我不确定在编写查询时如何为账单和帐户类创建关系。我遇到的问题是我将 accountId 存储在数据库中,但是我想从 toAccountId 和 fromAccountId 中显示用户的名字和姓氏。

课程

public class Bill
{
    public int BillId { get; set; }
    public string BillName { get; set; }
    public string BillDescription { get; set; }
    public decimal Price { get; set; }
    public DateTime DateCreated { get; set; }
    public DateTime? DateDue { get; set; }
    public int FromAccountId { get; set; }
    public int ToAccountId { get; set; }
}

public class Account
{
    public int AccountId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string MobilePhone { get; set; }
    public string BankAccountNumber { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
    public DateTime LastLogin { get; set; }
}

public class HomeViewModel
{
    public IEnumerable<Bill> Bills { get; set; } 
}

在控制器中

private IBillRepository repository;
public ViewResult Home()
{
    int userID = 1;
    HomeViewModel viewModel = new HomeViewModel
    {
        Bills = repository.Bills
            .OrderByDescending(b => b.DateCreated)
            .Where(b => b.FromAccountId.Equals(userID))
            .Take(amountOfBillsOnPageOnLoad)
    };
    return View(viewModel);
}
4

3 回答 3

1

这可能会有所帮助 // 使用导航属性

public class Bill
{
    public int BillId { get; set; }
    public string BillName { get; set; }
    public string BillDescription { get; set; }
    public decimal Price { get; set; }
    public DateTime DateCreated { get; set; }
    public DateTime? DateDue { get; set; }
    public int FromAccountId { get; set; }
    public int ToAccountId { get; set; }

    public Account Accounts { get; set; }  // Navigation Property to the Account
}

在您看来,您可以像这样访问 Account 对象属性。

@model.Accounts.FirstName
于 2012-07-09T10:44:18.300 回答
0

就像是...

 Bills = repository.Bills.Include("Account")
            .OrderByDescending(b => b.DateCreated)
            .Where(b => b.FromAccountId.Equals(userID))
            .Take(amountOfBillsOnPageOnLoad)

...应该让你去。请注意使用“包含”将数据从相关表中提取到查询中。您也可以使用这种语法(实际上可能是首选).Include(b => b.Account)

于 2012-07-09T10:29:24.407 回答
0

你可以这样做,

  public class Bill
    {
        public int BillId { get; set; }
       //...........
        public Account FromAccount { get; set; }
        public Account ToAccount { get; set; }
        public int FromAccountId { get; set; }
        public int ToAccountId { get; set; }
    }


    public class Account
    {
        public int AccountId { get; set; }
     //..............
    }
于 2012-07-09T11:04:43.427 回答