2013-01-24 86 views
0

我是ASP.NET MVC的新手,並且在其中有聯繫人信息的模型,但也包含聯繫人Notes的列表。該模型是這樣的:模型中的MVC4列表

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

在我加載註釋到投資者的物體,像這樣的控制器:

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表自動加載到投資者,而無需在控制器中執行此操作。有任何想法嗎?

回答

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可以自動加載註釋Investor

+0

實際上,我遇到了LINQ問題。它應該工作,但我收到「無效的列名'Investor_Id'」的錯誤。「這對我沒有意義。我可以減少語句爲:var notes = db.Notes.ToList();並仍然有相同的錯誤。 – BlooSki

+0

我會添加Note類或Notes表中沒有'Investor_Id'。 – BlooSki

+0

@BlooSki有命名約定,也許EF試圖找到PK,嘗試添加'[Key]'屬性。 – webdeveloper