1

我正在尝试获取帖子所有者的用户名。到目前为止,这是我尝试过的。

var model = db.Posts
            .OrderByDescending(d => d.PostDate)
            .Select(p => new PostViewModel
            {
                Id = p.Id,
                Title = p.Title,
                Link = p.Link,
                Description = p.Description,
                Username = db.UserProfiles.Find(p.UserId).UserName
            }).ToList();

我正在尝试从我的域模型中获取帖子并将其存储到视图模型中,除了通过作者 ID 获取用户名之外,一切正常。我收到此错误:

Method 'Project.Models.UserProfile Find(System.Object[])' declared on type 'System.Data.Entity.DbSet`1[Project.Models.UserProfile]' cannot be called with instance of type 'System.Data.Objects.ObjectQuery`1[Project.Models.UserProfile]'

那么我怎样才能得到作者的用户名呢?

4

1 回答 1

2

必须有某种方法可以从 Post 导航到 UserProfile。使用 .Include() 拉入必要的关系,然后访问它。例如,如果 Post 有一个名为 UserProfile 的可导航属性,请执行以下操作。

var model = db.Posts
        .Include( "UserProfile" )
        .OrderByDescending(d => d.PostDate)
        .Select(p => new PostViewModel
        {
            Id = p.Id,
            Title = p.Title,
            Link = p.Link,
            Description = p.Description,
            Username = p.UserProfile.UserName
        }).ToList();
于 2014-02-04T15:50:16.990 回答