0

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?

4

1 に答える 1

0

ご覧のとおり、Entity Framework を使用しています。

string query = "SELECT * FROM Notes " +
    "WHERE ContactTableId = 'Investors' AND ContactId = " + id +
    " ORDER BY DateCreated DESC";
var notes = db.Database.SqlQuery<Note>(query).ToList();

このコードは、次のような LINQ に置き換えることができます。

db.Notes.Where(x => x.ContactTableId == "Investors" && x.ContactId == id).OrderByDescending(x => x.DateCreated).ToList()

このコードは決して HttpNotFound を返しません:

if (investor == null)
{
    return HttpNotFound();
}

NullReferenceExceptionここで例外が発生するため:

investor.Notes = notes;

リレーションを含むテーブルを作成すると、EF は自動的に Notes を読み込むことができます。Investor

于 2013-01-24T07:55:49.253 に答える