I'm using ASP.NET MVC, SQL Server 2008 and Forms Authentication. Suppose I am building a question-answer site like SO.
Here is the issue I am running into:
Users can view almost all the questions when not logged in, like they can on SO. Question-fetching query etc is almost written.
Now, if a user is logged in, he should also be able to tell whether he has already voted or "favorited" this question, like on SO.
- Do I go back and rewrite all my queries to includ开发者_如何学Goe userIdInt parameter even when the user is anonymous just to know this information?
- Or when a user logs in, I store what all he has voted on and keep track of that throughout his session?
Both seem cumbersome, but 1) seems more efficient at least. Anybody know how SO does this or more efficient way?
I think it doesn't keep track of whether the user has voted, but it does seem to keep track of whether the user has "favorited" that question.
You could use multiple interfaces, one for anonymous access, and one for authenticated access, and perform different queries for each:
http://en.wikipedia.org/wiki/Interface_segregation_principle
// Just example code - not asp.net-mvc
interface IAnonymousReader
{
IEnumerable<Answer> GetAnswers(int page, int countPerPage);
}
interface IAuthenticatedReader
{
IEnumerable<AuthenticatedAnswer> GetAnswers(int page, int countPerPage,
int userId);
// An alternative here is to get userId from concrete class, and pass in ctor
}
This would require that you write multiple queries, or that you get back data that you just throw away. You can avoid code duplication by constructing your query programatically. You could avoid writing the queries to begin with by using ORM.
As for the data, you could normalize the data, so that voting information is in a separate table, but still bound to the answer. When you're doing the query for anonymous users, simply don't join/query that table.
精彩评论