无法将SuggestionComment隐式转换为ICollection <suggestioncomment> </suggestioncomment>

时间:2014-02-03 19:46:21

标签: entity-framework

我确切地知道错误说的是什么;但是,我不知道如何从我的代码中获得我想要的功能。

 var item = from l in context.Suggestions
                       join a in context.SuggestionVotes on l.id equals a.SuggestionId
                       join b in context.SuggestionComments on l.id equals b.SuggestionId
                       join c in context.Users on b.UserId equals c.id
                       where l.id == id
                       select new Suggestion
                       {
                           id = l.id,
                           Title = l.Title,
                           Description = l.Description,
                           PosterId = l.PosterId,
                           SuggestionComments = b
                       };

我正在尝试将SuggestionComments(ICollection<SuggestionComment>)设置为等于我的表SuggestionComments中属于我原始Suggestion对象的所有记录。

建议

int id (PK)
string Title
string Description

SuggestionComment

int id (PK)
int SuggestionId (FK)

1 个答案:

答案 0 :(得分:0)

您的直接问题是,bSuggestionComment个实例,而不是SuggenstionComment的集合,并且您尝试将其设置为SuggestionComments导航集合属性一个Suggestion对象。

但你真正的问题是你正在使用连接 - 你为什么不使用导航属性?例如:

context.Suggestions
    .Where( s => s.Id == id )
    .Select( s => new Suggestion
    {
        id = s.id,
        Title = s.Title,
        Description = s.Description,
        PosterId = s.PosterId,
        SuggestionComments = s.SuggestionComments
    } );

澄清情况的评论后更新:

var suggestion = context.Suggestions
    .Where( s => s.Id == id )
    .Select( s => new
    {
        Suggestion = s,
        Comments = s.SuggestionComments,
        CommentUsers = s.SuggestionComments.Select( sc => sc.User )
    }
    .Single()
    .Select( at => at.Suggestion )
    .Single();

 // if tracking is enabled in your DbContext, the suggestion object
 //  will have its SuggestionComments collection loaded
 //  as well as each SuggestionComment's User property