2015-12-30 34 views
2

我試圖用視圖發送數據並將其打印出來,但由於我對C#很陌生,因此我正在努力掙扎。C# - 實體或複雜類型不能在LINQ to Entities查詢中構建

因此,這裏是我的模型視圖模型:

namespace P104.Models 
{ 
    public class ViewModel 
    { 
    } 

    public class Location 
    { 
     public int loc_id { get; set; } 
     public string loc_name { get; set; } 
    } 

    public class Competentie 
    { 
     public int Comp_id { get; set; } 
     public string competentie { get; set; } 
    } 

    public class MyViewModel 
    { 
     public User User { get; set; } 
     public IEnumerable<Locations> Locations { get; set; } 
     public IEnumerable<Competenties> Competenties { get; set; } 
    } 
} 

這是功能我在控制器

public ActionResult Details(int? id) 
{ 
    if (id == null) 
    { 
     return new HttpStatusCodeResult(HttpStatusCode.BadRequest); 
    } 
    User user = db.user.Find(id); 

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

    var competenties = 
     from usercomp in dbE.UserComp 
     join comp in dbE.Competenties on usercomp.fk_Comp_id equals comp.comp_id 
     where usercomp.fk_user_id == id 
     select new Competenties { competentie = comp.competentie }; 

    var locations = 
     from userloc in dbE.UserLoc 
     join loc in dbE.Locations on userloc.fk_location_id equals loc.loc_id 
     where userloc.fk_user_id == id 
     select new Locations { loc_name = loc.loc_name }; 

    var model = new MyViewModel 
    { 
     User = user, 
     Locations = locations.ToList(), // eagerly fetch the data that will be needed in the view 
     Competenties = competenties.ToList(), // eagerly fetch the data that will be needed in the view 
    }; 
    return View(model); 
} 

他就是我嘗試打印出來的觀點:

@foreach (var location in Model.Locations) 
{ 
    <dt>@location.locname</dt> 
    <dd>@location.locname</dd> 
} 
@foreach (var competentie in Model.Competenties) 
{ 
    <dt>@competentie.competentie</dt> 
    <dd>@competentie.competentie</dd> 
} 

我總是recevie此錯誤

實體或複雜類型「P104.Models.Locations」不能 在LINQ實體查詢構造。

我找到了一些解決方案,但我努力將它們應用於我的代碼,因此它們不起作用。 在此先感謝您的幫助

回答

3

你似乎已經得到了一個錯字這裏:

select new Locations { loc_name = loc.loc_name }; 

這應該是:

select new Location { loc_name = loc.loc_name }; 

你是突出對被稱爲Location的模式,而不是Locations 。目前還不清楚Locations模型是什麼,因爲你沒有在你的問題中顯示。

當然,適應相應的視圖:

@foreach (var location in Model.Locations) 
{ 
    <dt>@location.loc_name</dt> 
    <dd>@location.loc_name</dd> 
} 

通過我將爲您推薦以下標準的C#命名約定的方式。這個約定規定,在C#中,屬性名稱應該以大寫字母開頭,不包含_。所以基本上你寧願使用LocationName或者只使用Name而不使用loc_name。您的Competentie模型的評論相同。

+0

而突然我得到這個錯誤無效的對象名'dbo.UserComps'。該數據庫被命名爲'dbo.UserComp',我不知道他從哪裏得到這個。 – Nicolas

+0

真的很難幫助,而不知道'dbo'在你的上下文或'UserComp'中。我建議你問一個新問題,並請嘗試具體。只顯示你的代碼的相關部分。在這種情況下,這將是您的EF DataContext定義和LINQ查詢。 –

相關問題