Search code examples
c#asp.net.netasp.net-mvcauthor

ASP.NET MVC get content owner username


I'm trying to get username of the post owner. Here is what so far I've tried.

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();

I am trying to get post from my domain model and store it to view model, and everything works except getting username by author id. I' getting this error:

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]'

So how I could get a username of the author?


Solution

  • There must be some way to navigate from a Post to a UserProfile. Use .Include() to pull in the necessary relationships and then access that. For example, if the Post has a navigable property called UserProfile, do the following.

    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();