模型中的MVC4列表

时间:2013-01-24 07:11:11

标签: asp.net-mvc-4

我是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; }
}

在Controller中,我将Notes加载到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,而无需在控制器中执行。有什么想法吗?

1 个答案:

答案 0 :(得分: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可以自动加载Investor

的Notes
相关问题