In my database, UserID is a foreign key that goes to the UserId column in my aspnet_Users table. Consider post to be like a post in a forum, a blog entry, whatever... When I list the posts in my view I want to display the username of the person instead of the guid. How can I retrieve this and send it to my view at the same time?
namespace MySite.Models
{
public class Post
{
public Guid PostID { get; set; }
public Guid UserID { get; set; }
public DateTime PostedDate { get; set; }
public string PostContent { get; set; }
}
public class DBContexts : DbContext
{
public DbSe开发者_JS百科t<Post> Posts { get; set; }
}
}
public class PostController : Controller
{
DBContexts db = new DBContexts();
public ActionResult Index()
{
var posts = db.Posts.ToList();
return View(posts);
}
}
One alternative would be to put the aspnet_Users table into your Entity Model, and then do a join to retrieve the additional user information when you request the posts.
var posts = (from p in db.Posts
join u in db.AspNet_Users on p.UserId equals u.UserId
select new { Post = p, Username = u.UserName }).ToList();
I believe that you could select the entire entity p here into an anonymous type, rather than having to select each column. If not in this syntax, a slightly different one such as using groupby would do it.
Incidently I would advise you recreate the ObjectContext for each request, and also consider using a repository pattern so you can avoid repeating more complex calls like this, and keep them in a single place. (It's also great for unit testing).
Alternatively, if you don't want to include the aspnet_Users table in your entity model, you could create a view in the database, and then add it as a View to the entity model. Perhaps even instead of the normal Posts table, but you wouldn't be able to insert entities to the view, and I assume this is functionality you will want.
EDIT (Using in the view):
The variable posts is an anonymous type. The C# compiler is able to let you use this in a strongly typed way within the method it is defined, but once you leave that scope, it is only known as an object. This is why all the properties are not visible in the view.
My advice would be to define a ViewModel class, which contains this data through compile time properties. For example:
public class PostViewModel
{
public Post Post { get; set; }
public string Username { get; set; }
}
Then you can modify the above query to be something more like:
...select new PostViewModel { Post = p, Username = u.UserName }).ToList();
If you make your MVC view extend ViewPage<PostViewModel>, then you should now be able to easily access the Post and Username properties on your Model.
You can always use the viewbag to send additional info to your view.
Relevant.
精彩评论