简体   繁体   中英

How do I add select parameters when reading data for the View?

I am making an MVC 3 web application in asp.net. It is supposed to be like a little community where users can send messages to each other (and later on also to specified groups of people). So in my database I have the tables Users and Messages. A row in Messages (a message) contains both sender and receiver (a foreign key to the Users table) plus some other info such as title, send date and of course the message text.

When a user come to the index page for logged in users, I want to show all messages that have been sent to this user, or sent from this user. Therefore, when reading the messages from the Messages table I want to use a parameter, the id of the logged in user (which I can access in my controller). So I have the parameter but I don't know how to use it when getting the results. I know there must be a way to do this correctly instead of putting in a bunch of sql and starting connections right in the code the ugly way.

As you maybe can see now, all the messages from the table will be retrieved and sent to the View for displaying it to the user.

The CommunityEntities line is part of the whole Entity Framework thing, not exactly sure how that stuff works yet, although I have been following some tutorials:

( Creating-an-entity-framework-data-model-for-an-asp-net-mvc-application )

( Mvc-music-store-part-1 ).

UserController.cs:

...

CommunityEntities db = new CommunityEntities();

public ActionResult Index()
    {
        var messages = db.Messages.ToList();
        return View(messages);
    }

...

CommunityEntities.cs:

public class CommunityEntities : DbContext
{
    public DbSet<User> Users { get; set; }        
    public DbSet<Message> Messages { get; set; }
}

EDIT: I did try that thing with db.Database.SqlQuery(...) but that seemed wrong, seeing as the point is to do this correctly and "neat". This is for my education and my teachers are going to be picky at the structure of the application.

您需要一个where子句:

var messages = db.Messages.Where( m => m.SentById == id || m.SentToId == id ).ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM