Using LinQ to access multiple tables. What is the correct way to join these tables with LinQ to be the same as SQL Query?

huangapple go评论52阅读模式
英文:

Using LinQ to access multiple tables. What is the correct way to join these tables with LinQ to be the same as SQL Query?

问题

I am trying to access all the tables in the data warehouse that I created for an experimental project using Lin-Q and I just don't seem to understand how to access every table regarding the data structure, but can easily query using SQL Server to get my results. I can access the DimLocation table, but none of the others. I think in the controller is the right approach, but don't know how to select each column of every table using Lin-Q. Any help would be greatly appreciated!

My Program: [GlobalCommandCenter][1]

SQL Query Result Join Tables:

[![enter image description here][2]][2]

Tables To Join From Entities Framework:
[![enter image description here][3]][3]

LinQ I Created to Join Tables (Need help to join all tables as SQL):
[![enter image description here][4]][4]

I can use one table and it works just fine, but I get this error when I try to do multiple tables as Michael describes to do.
[![enter image description here][5]][5]

Added multiple joins code in the controller:

LocationDatas = (List<DimLocation>)(from c in entities.DimLocations
             join f in entities.FactInventories
             on c.LocationId equals f.LocationId
             join p in entities.DimProductInventories
             on f.ProductId equals p.ProductId
             join dd in entities.DimDates
             on f.DateSK equals dd.DateSK
             join dt in entities.DimTimes
             on f.TimeSK equals dt.TimeSK
             where c.ContinentName == continent && c.CountryName == country 
             && c.CountryName == c.CountryName && c.ContinentName == c.ContinentName 
             && c.ContinentName == continent || string.IsNullOrEmpty(continent) || string.IsNullOrEmpty(country) 
             && c.ContinentName == continent
             select new 
             {
                 c.LocationId,
                 c.ContinentName,
                 c.CountryName,
                 c.RegionName,
                 c.CityName,
                 p.ProductName,
                 f.ProductPrice,
                 f.ProductQty,
                 dd.StandardDate,
                 dt.StandardTime
             }),

Error I get after adding multiple joins code:
[![enter image description here][6]][6]

I edited the call to the model, did away with the bracket and added a semicolon at the very end of it. I then added var to each output with a semi colon at the very end of each statement. After that I get errors on the view.
[![Error Controller Problem][7]][7]
Compilation Error on View (IEnumerable Compatible Error in Razor View?):
[![Compilation Error on View][8]][8]

SQL Query:

SELECT ContinentName, CountryName, RegionName, CityName, ProductName, 
finv.ProductPrice, 
finv.ProductQty, StandardDate, StandardTime 
FROM DimLocation dloc
INNER JOIN FactInventory finv ON finv.LocationId = dloc.LocationId
INNER JOIN DimProductInventory dprod ON finv.ProductId = dprod.ProductId
INNER JOIN DimDate ddat ON finv.DateSK = ddat.DateSK
INNER JOIN DimTime dtim ON finv.TimeSK = dtim.TimeSK

SELECT * FROM FactInventory   
SELECT * FROM DimLocation
SELECT * FROM DimDate            
SELECT * FROM DimTime
SELECT * FROM DimProductInventory

Controller:

using ClassLibraryDAL.DAL;
using OperationsCommandCenter.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace OperationsCommandCenter.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            CommandCenterModel model = PopulateModel(null, null);

            return View(model);
        }

        //Controls DropDownList.
        [HttpPost]
        public ActionResult Index(string continent, string country)
        {
            CommandCenterModel model = PopulateModel(continent, country);

            return View(model);
        }

        //Population Controller. References list selection.
        public static CommandCenterModel PopulateModel(string continent, string country)
        {
            using (GlobalCommandCenter3Entities entities = new GlobalCommandCenter3Entities())
            {
                CommandCenterModel model = new CommandCenterModel()
                {
                    //Join all the tables together and extract the information into one web grid. 
                    LocationDatas = (from c in entities.DimLocations
                                     join f in entities.FactInventories
                                     on c.LocationId equals f.LocationId

                                     join p in entities.DimProductInventories
                                     on f.ProductId equals p.ProductId

                                     join dd in entities.DimDates
                                     on f.DateSK equals dd.DateSK

                                     join dt in entities.DimTimes
                                     on f.TimeSK equals dt.TimeSK
                                     where c.ContinentName == continent && c.CountryName == country && c.CountryName == c.CountryName 
                                     && c.ContinentName == c.ContinentName && c.ContinentName == continent || string.IsNullOrEmpty(continent) || 
                                     string.IsNullOrEmpty(country) && c.ContinentName == continent
                                     select  c).ToList(),  

                    Country = (from c in entities.DimLocations
                               orderby c.CountryName
                               where !string.IsNullOrEmpty(c.CountryName) && c.CountryName != null && continent == c.ContinentName
                               select new SelectListItem { Text = c.CountryName, Value = c.CountryName }).Distinct().ToList(),

                    Continent = (from c in entities.DimLocations
                                         orderby c.ContinentName
                                         where (c.ContinentName == c.ContinentName)
                                         select new SelectListItem { Text = c.ContinentName, Value = c.ContinentName }).Distinct().ToList(),
                    /*
                    Location = (from c in entities.DimLocations
                                     join f in entities.FactInventories
                                     on c.LocationId equals f.LocationId
                                     join p in entities.DimProductInventories
                                     on f.ProductId equals p.ProductId
                                     join dd in entities.DimDates
                                     on f.DateSK equals dd.DateSK
                                     join dt in entities.DimTimes
                                     on f.TimeSK equals dt.TimeSK
                                     where c.ContinentName == continent && c.CountryName == country && c.CountryName == c.CountryName 
                                    && c.ContinentName == c.ContinentName && c.ContinentName == continent || string.IsNullOrEmpty(continent) || 
                                    string.IsNullOrEmpty(country) && c.ContinentName == continent
                                     select new { c.ContinentName, c.CountryName, c.RegionName, c.CityName, f.ProductPrice, 
                                    f.ProductQty, dd.StandardDate, dt.StandardTime }).ToList(),
                    */

                };
                //Allow to stay on selection. 
                model.SectionCity = continent;
                return model;
            }
        }
    }
}

Model:

using ClassLibraryDAL.DAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace OperationsCommandCenter.Models
{
    public class CommandCenterModel
    {
        public List<DimLocation> LocationDatas { get; set; }
        public List<DimProductInventory> ProductInventory { get; set; }
        public List<SelectListItem> Country { get; set; } 
        public List<SelectListItem> Continent { get; set; } 

        public List<SelectListItem> ProductName { get;

<details>
<summary>英文:</summary>

I am trying to access all the tables in the data warehouse that I created for an experimental project using Lin-Q and I just don&#39;t seem to understand how to access every table regarding the data structure, but can easily query using SQL Server to get my results.  I can access the DimLocation table, but none of the others. I think in the controller is the right approach, but don&#39;t know how to select each column of every table using Lin-Q. Any help would be greatly appreciated!

My Program: [GlobalCommandCenter][1]


SQL Query Result Join Tables:

[![enter image description here][2]][2]

Tables To Join From Entities Framework:
[![enter image description here][3]][3]

LinQ I Created to Join Tables (Need help to join all tables as SQL): 
[![enter image description here][4]][4]

I can use one table and it works just fine, but I get this error when I try to do multiple tables as Michael describes to do. 
[![enter image description here][5]][5]

Added multiple joins code in the controller:

          			LocationDatas = (List&lt;DimLocation&gt;)(from c in entities.DimLocations
							 join f in entities.FactInventories
							 on c.LocationId equals f.LocationId
							 join p in entities.DimProductInventories
							 on f.ProductId equals p.ProductId
							 join dd in entities.DimDates
							 on f.DateSK equals dd.DateSK
							 join dt in entities.DimTimes
							 on f.TimeSK equals dt.TimeSK
							 where c.ContinentName == continent &amp;&amp; c.CountryName == country 
							 &amp;&amp; c.CountryName == c.CountryName &amp;&amp; c.ContinentName == c.ContinentName 
							 &amp;&amp; c.ContinentName == continent || string.IsNullOrEmpty(continent) || string.IsNullOrEmpty(country) 
							 &amp;&amp; c.ContinentName == continent
							 select new 
							 {
								 c.LocationId,
								 c.ContinentName,
								 c.CountryName,
								 c.RegionName,
								 c.CityName,
								 p.ProductName,
								 f.ProductPrice,
								 f.ProductQty,
								 dd.StandardDate,
								 dt.StandardTime
							 }),

Error I get after adding multiple joins code:
[![enter image description here][6]][6]

I edited the call to the model, did away with the bracket and added a semicolon at the very end of it. I then added var to each output with a semi colon at the very end of each statement. After that I get errors on the view. 
[![Error Contoller Problem][7]][7]
Compilation Error on View (IEnumerable Compatible Error in Razor View?):
[![Compilation Error on View][8]][8]

    public static CommandCenterModel PopulateModel(string continent, string country)
    {
    	using (GlobalCommandCenter3Entities entities = new GlobalCommandCenter3Entities())
    	{
    		**CommandCenterModel model = new CommandCenterModel()
    		{**
    			//Join all the tables together and extract the information into one web grid. 
    			LocationDatas = (from c in entities.DimLocations
    							 join f in entities.FactInventories
    							 on c.LocationId equals f.LocationId
    							
    							 join p in entities.DimProductInventories
    							 on f.ProductId equals p.ProductId
    							 
    							 join dd in entities.DimDates
    							 on f.DateSK equals dd.DateSK
    
    							 join dt in entities.DimTimes
    							 on f.TimeSK equals dt.TimeSK
    							 where c.ContinentName == continent &amp;&amp; c.CountryName == country &amp;&amp; c.CountryName == c.CountryName 
    							 &amp;&amp; c.ContinentName == c.ContinentName &amp;&amp; c.ContinentName == continent || string.IsNullOrEmpty(continent) 
    							 || string.IsNullOrEmpty(country) &amp;&amp; c.ContinentName == continent
                                 select  c).ToList(),	 
    
    			Country = (from c in entities.DimLocations
    					   orderby c.CountryName
    					   where !string.IsNullOrEmpty(c.CountryName) &amp;&amp; c.CountryName != null &amp;&amp; continent == c.ContinentName
    					   select new SelectListItem { Text = c.CountryName, Value = c.CountryName }).Distinct().ToList(),
     
    
    			Continent = (from c in entities.DimLocations
    								 orderby c.ContinentName
    								 where (c.ContinentName == c.ContinentName)
    								 select new SelectListItem { Text = c.ContinentName, Value = c.ContinentName }).Distinct().ToList(),
    			/*
    			Location = (from c in entities.DimLocations
    							 join f in entities.FactInventories
    							 on c.LocationId equals f.LocationId
    							 join p in entities.DimProductInventories
    							 on f.ProductId equals p.ProductId
    							 join dd in entities.DimDates
    							 on f.DateSK equals dd.DateSK
    							 join dt in entities.DimTimes
    							 on f.TimeSK equals dt.TimeSK
    							 where c.ContinentName == continent &amp;&amp; c.CountryName == country &amp;&amp; c.CountryName == c.CountryName &amp;&amp; c.ContinentName == c.ContinentName &amp;&amp; c.ContinentName == continent || string.IsNullOrEmpty(continent) || string.IsNullOrEmpty(country) &amp;&amp; c.ContinentName == continent
    							 select new { c.ContinentName, c.CountryName, c.RegionName, c.CityName, f.ProductPrice, f.ProductQty, dd.StandardDate, dt.StandardTime }).ToList(),
    			*/
    
    		};
    		//Allow to stay on selection. 
    		model.SectionCity = continent;
    		return model;
    	}
    }

SQL Query:


				
        SELECT ContinentName, CountryName, RegionName, CityName, ProductName, 
        finv.ProductPrice, 
        finv.ProductQty, StandardDate, StandardTime 
        FROM DimLocation dloc
        INNER JOIN FactInventory finv ON finv.LocationId = dloc.LocationId
        INNER JOIN DimProductInventory dprod ON finv.ProductId = dprod.ProductId
        INNER JOIN DimDate ddat ON finv.DateSK = ddat.DateSK
        INNER JOIN DimTime dtim ON finv.TimeSK = dtim.TimeSK


                    SELECT * FROM FactInventory   
					SELECT * FROM DimLocation
					SELECT * FROM DimDate            
					SELECT * FROM DimTime
					SELECT * FROM DimProductInventory



Controller:

        using ClassLibraryDAL.DAL;
        using OperationsCommandCenter.Models;
        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Web;
        using System.Web.Mvc;

        namespace OperationsCommandCenter.Controllers
       {
	    public class HomeController : Controller
	   {
		// GET: Home
		public ActionResult Index()
		{
			CommandCenterModel model = PopulateModel(null, null);

			return View(model);
		}

		//Controls DropDownList.
		[HttpPost]
		public ActionResult Index(string continent, string country)
		{
			CommandCenterModel model = PopulateModel(continent, country);

			return View(model);
		}

		//Population Controller. References list selection.
		public static CommandCenterModel PopulateModel(string continent, string country)
		{
			using (GlobalCommandCenter3Entities entities = new 
            GlobalCommandCenter3Entities())
			{
				CommandCenterModel model = new CommandCenterModel()
				{
					//Join all the tables together and extract the information into one web 
                      grid. 
					LocationDatas = (from c in entities.DimLocations
									 join f in entities.FactInventories
									 on c.LocationId equals f.LocationId
									 
									 join p in entities.DimProductInventories
									 on f.ProductId equals p.ProductId
									 
									 join dd in entities.DimDates
									 on f.DateSK equals dd.DateSK

									 join dt in entities.DimTimes
									 on f.TimeSK equals dt.TimeSK
									 where c.ContinentName == continent &amp;&amp; c.CountryName == 
            country &amp;&amp; c.CountryName == c.CountryName &amp;&amp; c.ContinentName == c.ContinentName 
            &amp;&amp; c.ContinentName == continent || string.IsNullOrEmpty(continent) || 
            string.IsNullOrEmpty(country) &amp;&amp; c.ContinentName == continent
									 select  c).ToList(),  

					Country = (from c in entities.DimLocations
							   orderby c.CountryName
							   where !string.IsNullOrEmpty(c.CountryName) &amp;&amp; c.CountryName 
             != null &amp;&amp; continent == c.ContinentName
							   select new SelectListItem { Text = c.CountryName, Value = 
                               c.CountryName }).Distinct().ToList(),


					Continent = (from c in entities.DimLocations
										 orderby c.ContinentName
										 where (c.ContinentName == c.ContinentName)
										 select new SelectListItem { Text = c.ContinentName, 
                                         Value = c.ContinentName }).Distinct().ToList(),
					/*
					Location = (from c in entities.DimLocations
									 join f in entities.FactInventories
									 on c.LocationId equals f.LocationId
									 join p in entities.DimProductInventories
									 on f.ProductId equals p.ProductId
									 join dd in entities.DimDates
									 on f.DateSK equals dd.DateSK
									 join dt in entities.DimTimes
									 on f.TimeSK equals dt.TimeSK
									 where c.ContinentName == continent &amp;&amp; c.CountryName == 
           country &amp;&amp; c.CountryName == c.CountryName &amp;&amp; c.ContinentName == c.ContinentName 
          &amp;&amp; c.ContinentName == continent || string.IsNullOrEmpty(continent) || 
          string.IsNullOrEmpty(country) &amp;&amp; c.ContinentName == continent
									 select new { c.ContinentName, c.CountryName, 
           c.RegionName, c.CityName, f.ProductPrice, f.ProductQty, dd.StandardDate, 
           dt.StandardTime }).ToList(),
					*/

				};
				//Allow to stay on selection. 
				model.SectionCity = continent;
				return model;
			}
		}
	    }
        }

Model: 

       using ClassLibraryDAL.DAL;
       using System;
       using System.Collections.Generic;
       using System.Linq;
       using System.Web;
       using System.Web.Mvc;

       namespace OperationsCommandCenter.Models
       {
	   public class CommandCenterModel
	   {
		public List&lt;DimLocation&gt; LocationDatas { get; set; }
		public List&lt;DimProductInventory&gt; ProductInventory { get; set; }
		public List&lt;SelectListItem&gt; Country { get; set; } 
		public List&lt;SelectListItem&gt; Continent { get; set; } 

		public List&lt;SelectListItem&gt; ProductName { get; set; } 

		//public List&lt;DimLocation&gt; Location { get; set; }

		public string SectionCity { get; set; }

	}
    }


View: 


      @model  OperationsCommandCenter.Models.CommandCenterModel

    @{
    ViewBag.Title = &quot;Home Page&quot;;
    string Country = Model.Country.ToString();
    string SectionCity = Model.SectionCity;

     WebGrid webGrid = new WebGrid(source: Model.LocationDatas, canPage: true, canSort: 
       true, sortDirectionFieldName: &quot;ContinentName, CountryName, RegionName, CityName&quot;, 
       rowsPerPage: 20);
    webGrid.Pager(WebGridPagerModes.All);

    }

    &lt;!DOCTYPE html&gt;

    &lt;head&gt;
    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width&quot; /&gt;

    &lt;title&gt;Global Command Center&lt;/title&gt;
    &lt;link href=&quot;@Url.Content(&quot;~/Content/YardDogStyle.css&quot;)&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; 
    /&gt;
    &lt;link href=&quot;@Url.Content(&quot;~/Scripts/jquery-3.4.1.min.js&quot;)&quot; rel=&quot;stylesheet&quot; 
     type=&quot;text/css&quot; /&gt;
    &lt;link href=&quot;@Url.Content(&quot;~/Scripts/bootstrap.min.js&quot;)&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; 
     /&gt;

    &lt;script src=&quot;~/Scripts/bootstrap.min.js&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;~/Scripts/jquery-3.4.1.min.js&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;Scripts/jquery-1.4.1.min.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;~/Scripts/jquery-1.4.1.min.js&quot;&gt;&lt;/script&gt;
   
    &lt;link href=&quot;~/Content/YardDogStyle.css&quot; rel=&quot;stylesheet&quot; /&gt;
    
      &lt;/head&gt;
      &lt;body&gt;
    &lt;div id=&quot;time&quot;&gt;&lt;/div&gt;
    &lt;div id=&quot;RowCount&quot;&gt;&lt;/div&gt;
    &lt;SCRIPT LANGUAGE=&quot;Javascript&quot;&gt;

        function checkTime(i) {
            if (i &lt; 10) {
                i = &quot;0&quot; + i;
            }
            return i;
        }
        function startTime() {
            var today = new Date();
            var h = today.getHours();
            var m = today.getMinutes();
            var s = today.getSeconds();

            // add a zero in front of numbers&lt;10
            m = checkTime(m);
            s = checkTime(s);
            document.getElementById(&#39;time&#39;).innerHTML = h + &quot;:&quot; + m + &quot;:&quot; + s; //Get the 
            time.
            document.getElementById(&#39;time&#39;).innerHTML = &quot;Date: &quot; + today; //Get the Date.
            t = setTimeout(function () {
                startTime()
            }, 500);
        }
        startTime();
    &lt;/SCRIPT&gt;
    &lt;script src=&quot;Scripts/jquery-1.4.1.min.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;Scripts/ScrollableGridPlugin.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
    &lt;script type=&quot;text/javascript&quot;&gt;
        $(document).ready(function () {
            $(&#39;#&lt;%=webGrid.ClientID %&gt;&#39;).Scrollable({
                ScrollHeight: 300
            });
            $(&#39;#&lt;%=webGrid.ClientID %&gt;&#39;).Scrollable({
                ScrollHeight: 300
            });
        });
    &lt;/script&gt;

    &lt;script src=&quot;Scripts/ScrollableGridPlugin.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;~/Scripts/ScrollableGridPlugin.js&quot;&gt;&lt;/script&gt;
    &lt;script type=&quot;text/javascript&quot;&gt;
        $(document).ready(function () {
            $(&#39;#&lt;%=webGrid.ClientID %&gt;&#39;).Scrollable({
                ScrollHeight: 300,
                Width: 467
            });
        });
    &lt;/script&gt;
    &lt;script type=&quot;text/javascript&quot;&gt;
        //Count the rows on the webGrid that are visible... is my intent with this code.
        function CountRows() {
            var totalRowCount = 0;
            var rowCount = 0;
            var gridView = document.getElementById(&quot;&lt;%=webGrid.ClientID %&gt;&quot;);
            var rows = gridView.getElementsByTagName(&quot;tr&quot;)
            for (var i = 0; i &lt; rows.length; i++) {
                totalRowCount++;
                if (rows[i].getElementsByTagName(&quot;td&quot;).length &gt; 0) {
                    rowCount++;

                }

            }
            var message = &quot;Total Row Count: &quot; + totalRowCount;
            message += &quot;\nRow Count: &quot; + rowCount;
            //alert(message);
            message = document.getElementById(&#39;RowCount&#39;).innerHTML = message;

            // return false;

        }
        CountRows();
    &lt;/script&gt;
    &lt;form id=&quot;formYardDog&quot; class=&quot;formYardDog&quot; runat=&quot;server&quot; method=&quot;post&quot;&gt;

        @{ int firstRecord = (webGrid.PageIndex * webGrid.RowsPerPage) + 1;
            int lastRecord = (webGrid.PageIndex * webGrid.RowsPerPage) + webGrid.Rows.Count;

            // webGrid.Rows..GetRowCount(DataGridViewElementStates.Visible);
        }
        &lt;div id=&quot;RowCountTop&quot;&gt;&lt;b&gt;Records: @firstRecord - @lastRecord of 
        @webGrid.TotalRowCount&lt;/b&gt;&lt;/div&gt;&lt;br /&gt;

        @using (Html.BeginForm(&quot;Index&quot;, &quot;Home&quot;, FormMethod.Post, new { @Id = &quot;formYardDog&quot; 
        }))
        {
            //Loop to Get Dictionary List Buttons with Distinct Section Values.
            for (int i = 0; i &lt; Model.Continent.Count; i++)
            {
             
                //If the SectionCity is not null, then back-ground color to red.

                if (@Model.Continent[i].Value == SectionCity)
                {

                    &lt;button name=&quot;@Html.NameFor(model =&gt; model.Continent)&quot; 
             value=&quot;@Model.Continent[i].Value&quot; id=&quot;ddlSectionButtons&quot; runat=&quot;server&quot; , new { 
            class=&quot;ddlSectionButtons&quot; onClick=&quot;focusMe(this);&quot; style=&quot;background-color: 
           #AFE1AF; color: black&quot; }&gt;@Model.Continent[i].Value&lt;/button&gt;

                }
                else
                {
                    // var Count = i;
                    &lt;!--  &lt;input type=&quot;submit&quot; name=&quot;Html.NameFor(model =&gt; model.Section)&quot; 
           value=Model.Section[i].Value id=&quot;ddlSectionButtons&quot; , new { 
         class=&quot;ddlSectionButtons&quot; onClick=&quot;focusMe(this);&quot; }/&gt; --&gt;
                    &lt;button name=&quot;@Html.NameFor(model =&gt; model.Continent)&quot; 
        value=&quot;@Model.Continent[i].Value&quot; id=&quot;ddlSectionButtons&quot; runat=&quot;server&quot; , new { 
           class=&quot;ddlSectionButtons&quot; onClick=&quot;focusMe(this);&quot; 
          }&gt;@Model.Continent[i].Value&lt;/button&gt;

                }

            }
            if (SectionCity == null || SectionCity == &quot;&quot;)
            {
                &lt;button text=&quot;All&quot; type=&quot;submit&quot; name=&quot;@Html.NameFor(model =&gt; 
         model.Continent)&quot; , new { onClick=&quot;focusMe(this);&quot; id=&quot;ddlSectionAllButton&quot; 
       class=&quot;ddlSectionAllButton&quot; placeholder=&quot;All&quot; style=&quot;background-color: #AFE1AF; 
          color: black&quot; })&gt;All&lt;/button&gt;
            }
            else
            {
                &lt;button text=&quot;All&quot; type=&quot;submit&quot; name=&quot;@Html.NameFor(model =&gt; 
        model.Continent)&quot; , new { onClick=&quot;focusMe(this);&quot; id=&quot;ddlSectionAllButton&quot; 
         class=&quot;ddlSectionButtons&quot; placeholder=&quot;All&quot; style=&quot;background-color: #045AC6; 
          color: white&quot; })&gt;All&lt;/button&gt;
            }


            &lt;br /&gt;
            //Section == Country    //ContinentLocation == PlantLocation
            @Html.DropDownListFor(model =&gt; model.Continent, Model.Continent, &quot;- Continent - 
          &quot;, new { onchange = &quot;document.forms[0].submit();&quot;, @id = &quot;ddlWarehouses&quot;, @class = 
          &quot;ddlWarehouses&quot; })
            @Html.DropDownListFor(model =&gt; model.Country, Model.Country, &quot; - Country -&quot;, new 
          { onchange = &quot;document.forms[0].submit();&quot;, @id = &quot;ddlSection&quot;, @class = 
          &quot;ddlSection&quot; })

            &lt;div id=&quot;content&quot;&gt;
                @webGrid.GetHtml(tableStyle: &quot;webgrid-table&quot;,
                                    headerStyle: &quot;webgrid-header&quot;,
                                    footerStyle: &quot;webgrid-footer&quot;,
                         //alternatingRowStyle: &quot;webgrid-alternating-row&quot;,
                         selectedRowStyle: &quot;webgrid-selected-row&quot;,
                                    rowStyle: &quot;webgrid-row-style&quot;,
                                      mode: WebGridPagerModes.All,
                          htmlAttributes: new { @id = &quot;webGrid&quot; },
                         columns: webGrid.Columns(
                         webGrid.Column(header: &quot;Actions&quot;, format:@&lt;span class=&quot;link&quot;&gt;
    &lt;a href=&quot;#&quot; class=&quot;collapse expand-btn&quot;&gt;Expand&lt;/a&gt;
    &lt;a href=&quot;#&quot; class=&quot;expand collapse-btn&quot;&gt;Collapse&lt;/a&gt;
    &lt;!--
    &lt;a class=&quot;Edit&quot; href=&quot;javascript:;&quot;&gt;Edit&lt;/a&gt;
    &lt;a class=&quot;Clear&quot; href=&quot;javascript:;&quot;&gt;Clear&lt;/a&gt;
    &lt;a class=&quot;Update&quot; href=&quot;javascript:;&quot; style=&quot;display:none&quot;&gt;Update&lt;/a&gt;
    &lt;a class=&quot;Cancel&quot; href=&quot;javascript:;&quot; style=&quot;display:none&quot;&gt;Cancel&lt;/a&gt;
        --&gt;
     &lt;/span&gt;),

       webGrid.Column(columnName: &quot;Country&quot;, header: &quot;Country&quot;, format: @&lt;div&gt;
                &lt;label id=&quot;ContinentLbl&quot; class=&quot;label&quot;&gt;&lt;a id=&quot;CountryNameLnk&quot; 
        href=&quot;javascript:;&quot;&gt;@item.ContinentName&lt;/a&gt;&lt;/label&gt;
                &lt;!--- &lt;input id=&quot;Location&quot; class=&quot;text&quot; type=&quot;text&quot; value=&quot;item.CountryName&quot; 
         style=&quot;display:none&quot; onkeyup=&quot;this.value = this.value.toUpperCase();&quot;/&gt; --&gt;
                &lt;br /&gt;
                &lt;label id=&quot;CountryLbl&quot; &gt;&lt;a id=&quot;RegioNameLnk&quot; href=&quot;#&quot; class=&quot;collapse 
      expand-btn&quot; &gt;@item.CountryName&lt;/a&gt;&lt;/label&gt;
                &lt;br /&gt;
                &lt;label id=&quot;RegionLbl&quot;  &gt;&lt;a id=&quot;CityNameLnk&quot;href=&quot;#&quot; class=&quot;collapse expand- 
       btn&quot; &gt;@item.RegionName&lt;/a&gt;&lt;/label&gt;
                &lt;br /&gt;
                &lt;label id=&quot;CityLbl&quot; class=&quot;expand collapse&quot; &gt;@item.CityName&lt;/label&gt;
            &lt;/div&gt;, style: &quot;CountryName&quot;),

       webGrid.Column(header: &quot;RowPageID&quot;, format: @&lt;div&gt;
      &lt;label id=&quot;LocationIDLbl&quot; class=&quot;label&quot;&gt;@item.LocationID&lt;/label&gt;
     &lt;/div&gt;, style: &quot;LocationID&quot;))),

                &lt;div id=&quot;RowCountBpttom&quot;&gt;&lt;b&gt;Records: @firstRecord - @lastRecord of 
       @webGrid.TotalRowCount&lt;/b&gt;&lt;/div&gt;
            &lt;/div&gt;
            &lt;br /&gt;
            &lt;div class=&quot;WebGridTable&quot;&gt;
            &lt;/div&gt;
        }
    &lt;/form&gt;

    &lt;script type=&quot;text/javascript&quot; 
      src=&quot;https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js&quot;&gt;&lt;/script&gt;
    &lt;script type=&quot;text/javascript&quot; 
       src=&quot;https://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;~/Scripts/YardDog.js&quot;&gt;&lt;/script&gt;
    &lt;script type=&quot;text/javascript&quot;&gt;
        //Expand the Nodes. 
        $(function () {
            $(&#39;.expand&#39;).hide();      // Default - hide the table row of Course information
            // and also hide the Collapse text from
            // Student information&#39;s action column

            $(&#39;.expand-btn, .collapse-btn&#39;).on(&quot;click&quot;, function () {
                var tr = $(this).parents(&#39;tr:first&#39;);
                tr.find(&#39;.expand, .collapse&#39;).toggle();    // toggle to display either 
      Expand or
                // Collapse text in the Student row

                tr.next().toggle();    // toggle to display table row with Course 
     information
            });
        });
    &lt;/script&gt;


      &lt;/body&gt;


  [1]: https://drive.google.com/file/d/1DP9vY4RdS9LcJJWqDt6G-DtRgKsEnOo2/view
  [2]: https://i.stack.imgur.com/hwhSH.jpg
  [3]: https://i.stack.imgur.com/A1i94.jpg
  [4]: https://i.stack.imgur.com/e4fDA.jpg
  [5]: https://i.stack.imgur.com/vlZ4y.jpg
  [6]: https://i.stack.imgur.com/mN7p0.jpg
  [7]: https://i.stack.imgur.com/v94A5.jpg
  [8]: https://i.stack.imgur.com/2Jeto.jpg

</details>


# 答案1
**得分**: 0

获取自定义投影作为查询结果,您可以选择将其选择为匿名类或创建另一个DTO用于此

由于您的代码是截图,无法复制,因此以下是修剪过的示例:

```csharp
var customProjection = from c in entities.DimLocations
                       join f in entities.FactInventories
                       on c.LocationId equals f.LocationId
                       select new {
                           c.ContinentName,
                           f.ProductPrice
                       }

通过这种方式,您可以访问来自不同表的字段。

英文:

To get a custom projection as a result of the query you can either select it to an anonymous class or create another DTO for this.

Trimmed example (due to your code being a screenshot - I can't copy it):

var customProjection = from c in entities.DimLocations
                       join f in entities.FactInventories
                       on c.LocationId equals f.LocationId
                       select new {
                           c.ContinentName,
                           f.ProductPrice
                       }

This way you can access fields from different tables.

huangapple
  • 本文由 发表于 2023年2月14日 05:05:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/75441185.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定