Join multiple Tables using Entity Framework in Linq query using C# in ASP.Net

Last Reply 3 months ago By dharmendr

Posted 3 months ago

I have 2 tables

first is tbl_News and 2nd is tbl_Category.

1st tables has ID,Description,Date,Status,City and CategoryID

2nd tables has Id,CategoryName.   i want to show all columns of news table but i want to show categoryName in place of CategoryID

var News = from n in tbl_News 
           join c in tbl_Category 
           on n.CategoryId equals c.CategoryID 
           select new { 
               ID = n.ID, 
               Description = n.Description, 
               Date = n.Date, 
               Status = n.Status, 
               City = n.City, 
               Category = c.CategoryName 
           }.ToList();

Here 1 got error tbl_category is type, not a valid in given context.

 

Posted 3 months ago

Hi mukesh1,

Check this example. Now please take its reference and correct your code.

Database

For this sample I have used of NorthWind database that you can download using the link given below.

Download Northwind Database

HTML

<asp:GridView runat="server" ID="gvProducts" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="ProductID" HeaderText="Product ID" />
        <asp:BoundField DataField="ProductName" HeaderText="Product Name" />
        <asp:BoundField DataField="UnitPrice" HeaderText="Price" DataFormatString="{0:N2}" />
        <asp:BoundField DataField="CategoryName" HeaderText="Category Name" />
        <asp:BoundField DataField="Description" HeaderText="Description" />
    </Columns>
</asp:GridView>

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        NorthwindModel.NorthwindEntities entities = new NorthwindModel.NorthwindEntities();
        var details = (from p in entities.Products
                        join c in entities.Categories
                        on p.CategoryID equals c.CategoryID
                        orderby p.ProductID
                        select new
                        {
                            ProductID = p.ProductID,
                            ProductName = p.ProductName,
                            UnitPrice = p.UnitPrice,
                            CategoryName = c.CategoryName,
                            Description = c.Description
                        }).Take(10).ToList();
        gvProducts.DataSource = details;
        gvProducts.DataBind();
    }
}

Screenshot

I agree, here is the link: https://www.e-iceblue.com/Introduce/spire-office-for-net-free.html