2015-12-30 36 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查询。 –

相关问题