I am pretty new to ASP.NET MVC, and have model with contact information in it, but also a list of contact Notes. The Models look like this:
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; }
}
In the Controller I am loading the Notes into the Investor object like this:
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);
}
While this works, I am thinking there is a more elegant, and 'best practice' way to automatically load the Notes table in to the Investor with foreign keys or some mechanism in the models without having to do it in the controller. Any ideas?