简体   繁体   English

使用Linq C#Asp.net显示来自不同表的数据

[英]Showing data from different tables with Linq C# Asp.net

How can I show data from different tables with linq & C#? 如何使用linq和C#显示来自不同表的数据? My project is a social network where the user should see all the public posts and the name and the image of the user that post that 我的项目是一个社交网络,用户应在其中看到所有公开帖子以及发布该帖子的用户的姓名和图像

For now I have this : 现在我有这个:

 var posts_public = from p in db.Posts
                       join e in db.Privacy on p.id_post equals e.id_post
                       join pu in db.Publish on p.id_post equals pu.id_post
                       join u in db.Users on pu.id_utilizador equals u.id_user
                       where e.id_privacy== 1
                       select new { p.text, u.name,u.image };
Viewbag.post = posts_public;

But when I want to show the data that I select show me like this: 但是,当我想显示选择的数据时,会像这样显示:

{ text = ola2, nome = André, image = /Content/Images\IMG_20150616_183508.jpg }

And I want that appear just the data like: 我希望仅显示如下数据:

ola2 
André
IMG_20150616_183508.jpg

Can someone help me ? 有人能帮我吗 ?

Thanks in advance :) 提前致谢 :)

You could create a result class and overload the ToString() method if this is something you are going to be doing all over the place. 您可以创建一个结果类并重载ToString()方法(如果要在整个地方执行此操作)。

Class: 类:

public class PublicResult
{
    public string Text { get; set; }
    public string Name { get; set; }
    public string ImagePath { get; set;}

    public override string ToString()
    {
        //return string.Format("{0}\n{1}\n{2}", Text, Name, ImagePath); <-- uncomment and delete other return if not using C# 6
        return $"{Text}\n{Name}\n{ImagePath}";
    }
}

Then in your query on the select do this: 然后在您选择的查询中执行以下操作:

var posts_public = from p in db.Posts
                   join e in db.Privacy on p.id_post equals e.id_post
                   join pu in db.Publish on p.id_post equals pu.id_post
                   join u in db.Users on pu.id_utilizador equals u.id_user
                   where e.id_privacy== 1
                   select new PublicResult{ Text = p.text, Name = u.name, ImagePath = u.image };

Now where ever you Console.WriteLine(posts_public) it will display as: 现在您在Console.WriteLine(posts_public)任何地方都将显示为:

ola2 
André
IMG_20150616_183508.jpg

Or if you are just doing this in a single place just do what I did in the ToString() method where you are outputting this result and not create the class. 或者,如果您只是在单个位置执行此操作,请执行我在ToString()方法中所做的操作,在该方法中您将输出此结果而不创建类。

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

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