Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat is the standard pattern to retrieve JOINed data from normalized tables?
    text
    copied!<p>I have the following simple "textbook" classes defined:</p> <pre><code> public class Product { public int Id { get; set; } public string Name { get; set; } public int Category { get; set; } } public class Category { public int Id { get; set; } public string Name { get; set; } } </code></pre> <p>The Category field in Product is an integer referencing the Id field in the Category class. In the database, it would be a foreign key relationship between the Product and Category tables.</p> <p>But my application would need to show the friendly name of the Category of a product.</p> <p><strong>Q1</strong>: Is it correct practice to define a new class as follows:</p> <pre><code> public class ProductJ : Product { public string CategoryName { get; set; } } </code></pre> <p>And then, if I now have a method getProductsJ as follows:</p> <pre><code> public class Test { public List&lt;Category&gt; Categories = new List&lt;Category&gt;() { ... }; public List&lt;Product&gt; Products = new List&lt;Product&gt;() { ... }; public List&lt;ProductJ&gt; getProductsJ() { var products = from p in Products join c in Categories on p.Category equals c.Id select new ProductJ { Id = p.Id, , Name = p.Name, CategoryName = c.Name }; //! return products.ToList(); } } </code></pre> <p><strong>Q2</strong>: Is the above the best way to retrieve a list of Products with Category names?</p> <p><strong>Q3</strong>: In the select statement (//!) is there a faster way to populate the fields of the base class Product linqwithout having to enter them one by one?</p> <p>Thanks.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload