简体   繁体   English

在读取视图数据时如何添加选择参数?

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

I am making an MVC 3 web application in asp.net. 我正在asp.net中制作MVC 3 Web应用程序。 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. 因此在我的数据库中,我有表Users和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. 消息中的一行(一条消息)包含发送者和接收者(Users表的外键)以及一些其他信息,例如标题,发送日期,当然还有消息文本。

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). 因此,当从“消息”表中读取消息时,我想使用一个参数,即已登录用户的ID(我可以在控制器中访问该ID)。 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. 我知道必须有一种正确执行此操作的方法,而不是放入一堆sql并以丑陋的方式在代码中正确启动连接。

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: 尽管我一直在关注一些教程,但CommunityEntities行是整个Entity Framework的一部分,虽然不能确切确定它的工作原理,但是仍然不确定:

( Creating-an-entity-framework-data-model-for-an-asp-net-mvc-application ) 为一个ASP.NET MVC应用程序创建一个实体框架数据模型

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

UserController.cs: UserController.cs:

...

CommunityEntities db = new CommunityEntities();

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

...

CommunityEntities.cs: 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". 编辑:我确实使用db.Database.SqlQuery(...)尝试了该操作,但这似乎是错误的,因为关键是要正确并“整洁”地执行此操作。 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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