我对 ASP.NET MVC 很陌生,并且有包含联系信息的模型,还有联系备注列表。模型如下所示:
public class Investor
{
public int Id { get; set; }
public string Name { get; set; }
public string Company { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Cell { get; set; }
public string Fax { get; set; }
[Display(Name="Address 1")]
public string Address1 { get; set; }
[Display(Name = "Address 2")]
public string Address2 { get; set; }
public string City { get; set; }
[StringLength(2, ErrorMessage = "State must be 2 characters")]
public string State { get; set; }
public string Zip { get; set; }
public List<Note> Notes { get; set; }
}
public class Note
{
[Key]
//[Column(Order = 0)]
public string ContactTableId { get; set; }
//[Key]
//[Column(Order = 1)]
public int? ContactId { get; set; }
public string note { get; set; }
public DateTime? DateCreated { get; set; }
}
在控制器中,我将注释加载到 Investor 对象中,如下所示:
public ActionResult Edit(int id = 0)
{
string query = "SELECT * FROM Notes " +
"WHERE ContactTableId = 'Investors' AND ContactId = " + id +
" ORDER BY DateCreated DESC";
var notes = db.Database.SqlQuery<Note>(query).ToList();
Investor investor = db.Investors.Find(id);
investor.Notes = notes;
if (investor == null)
{
return HttpNotFound();
}
return View(investor);
}
虽然这可行,但我认为有一种更优雅的“最佳实践”方式可以使用外键或模型中的某些机制自动将 Notes 表加载到 Investor 中,而无需在控制器中执行此操作。有任何想法吗?