c# - ASP.NET MVC 5 - 从数据库中选择数据的 LINQ 查询

标签 c# sql asp.net-mvc database linq

我正在使用 ASP.NET MVC 5 进行学校项目。该项目是关于创建社交网络的。用户登录后,他将在他的新闻源上看到所有公开的帖子。 不过,我在显示数据库中的公开帖子数据时遇到了问题。

这是数据库的脚本:

create table Utilizador(
    id_utilizador       integer     not null    identity(1,1),
    nome                varchar(50) not null,
    apelido             varchar(50) not null,
    username            varchar(15) not null    unique,
    pass                varchar(50) not null,
    email               varchar(50) not null    unique,
    sexo                char(1)     not null CHECK (sexo IN('M', 'F')),
    país                varchar(50) not null,
    imagem_perfil       varchar(50) not null,
    data_nascimento     date        not null,
    estado              int         not null default 2, --0->Bloqueado 1-Activo, 2-por activar
    primary key (id_utilizador),
    check (email LIKE '%@%.%')
    )

    create table Post(
    id_post         integer         not null identity(1,1),
    texto           varchar(400)    not null,
    primary key(id_post)
    )

    create table Publish_Post(
    id_post         integer         not null,
    id_utilizador   integer         not null,
    data            timestamp       not null,
    primary key(id_post),
    foreign key(id_post) references Post(id_post),
    foreign key(id_utilizador) references Utilizador(id_utilizador)
    )

    create table Privacy(
    id_privacidade  integer     not null identity(1,1), --> 1 public, 2 private
    nome            varchar(50) not null,
    primary key(id_privacidade)
    )

    create table Have_Privacy(
    id_post         integer     not null,
    id_privacidade  integer     not null,
    primary key(id_post),
    foreign key(id_post) references Post(id_post),
    foreign key(id_privacidade) references Privacidade(id_privacidade)
    )

让我来解释一下为什么我会这样创建数据库: 用户创建并发布了一些具有隐私值(1 或 2)的帖子。用户登录后,所有公共(public)帖子 (1) 都应出现在他的新闻源中。 到目前为止,我在 C# 中有这个 LINQ 查询:

var id_posts = from p in db.Posts
                           select p.texto;

            ViewBag.Posts = id_posts;

有人可以帮助我吗? 提前致谢:)

最佳答案

就这样吧

var id_posts = from p in db.Posts
           join hp in db.Have_Privacy on p.id_post equals hp.id_post
           join prv in db.Privacy on hp.id_privacidade equals prv.id_privacidade
           where prv.nome = 'Private'
           select p.texto;

说说进展情况

关于c# - ASP.NET MVC 5 - 从数据库中选择数据的 LINQ 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33978629/

相关文章:

sql - 应用程序搜索铁路连接

asp.net - *.cshtml 中的 UTF-8

asp.net - 将多项目 MVC4 解决方案部署到 Azure 失败

c# - 在 wpf 中绑定(bind) IEnumerable<IGrouping<string,BaseDto>> 类型对象

c# - SQLite GetChar返回null

c# - 如何在更新查询中将格式为 test@test1.com 的电子邮件地址传递给 Access DB

c# - 与 List <T> C# 重复

sql - SQL Server 中超过 VARCHAR(MAX) 值

sql - PostgreSQL RETURNING 因 REGEXP_REPLACE 而失败

asp.net - 让经典 ASP 从 web.config 文件中的 appsettings 读取 key