0

我对 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 中,而无需在控制器中执行此操作。有任何想法吗?

4

1 回答 1

0

如我所见,您正在使用实体框架。

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 forInvestor

于 2013-01-24T07:55:49.253 回答