我有以下简化类:
public class Customer
{
public int Id {get; set;}
public string FirstName {get; set;}
public string LastName {get; set;}
public List<Account> Accounts {get; set;}
}
public class Account
{
public int Id {get; set;}
public Customer Customer {get; set;}
public int CustomerId {get; set;}
public string AccountNumber {get; set;}
public double AccountBalance {get; set;}
public int? SupercededAccountId {get; set;}
}
因此,使用帐户类我需要访问取代帐户,这只是另一个帐户。我以超级账户的ID形式记录了被取消的账户。虽然我意识到这是丑陋和错误的,但我已经在Account类中添加了一个方法来检索我需要的帐户:
public Account SupercededAccount()
{
if (SupercededAccountId != null)
{
using (DataContext db = new DataContext())
{
Account supercededAccount = db.Accounts.Find(SupercededAccountId);
return supercededAccount;
}
}
else return null;
}
我不仅需要在帐户视图中访问已取代的Account对象,还需要访问报告和后台任务,因此我希望以某种方式成为Model类的一部分。获取我需要的超级账户价值的正确方法是什么?
答案 0 :(得分:1)
为已取代的帐户
创建导航器public class Account
{
[Key]
public int Id {get; set;}
[ForgienKey("Customer")]
public int CustomerId {get;set;}
//navigator to customer
public virtual Customer Customer {get; set;}
public string AccountNumber {get; set;}
public double AccountBalance {get; set;}
[ForgienKey("SupercededAccount")]
public int? SupercededAccountId {get; set;}
public virtual Account SupercededAccount {get;set;}
}
public class Customer
{
[Key]
public int Id {get; set;}
public string FirstName {get; set;}
public string LastName {get; set;}
public virtual ICollection<Account> Accounts {get; set;}
}