I created list of objects in controller and I would like show one of property in DropDownList. This is my controller:
public class HomeController : Controller
{
public ActionResult Index()
{
List<Product> product = new List<Product>();
product.Add(new Product() { ProductId = 1, Name = "apple", Price = 1.09 });
product.Add(new Product() { ProductId = 2, Name = "peach", Price = 1.57 });
product.Add(new Product() { ProductId = 3, Name = "banana", Price = 1.15 });
product.Add(new Product() { ProductId = 4, Name = "watermelon", Price = 4.50 });
product.Add(new Product() { ProductId = 5, Name = "melon", Price = 5.06 });
product.Add(new Product() { ProductId = 6, Name = "strawberries", Price = 6.99 });
product.Add(new Product() { ProductId = 7, Name = "raspberries", Price = 2.20 });
return View(product);
}
}
And I try use it into my View below but it return false. How can I use helper #Html.DropDownListFor?
#foreach(var name in Model.Name)
{
#Html.DropDownListFor(name.Name ,name.ToString())
}
I am assuming that for the Product class looks like:
public class Product
{
public int ProductId { get; set; }
public string Name { get; set; }
public double Price { get; set; }
}
And let us say that you have the following model:
public class ProductModel
{
public int MyProductId { get; set; }
}
And finally you have created the list of Products (like you have shown)
List<Product> product = new List<Product>();
produkt.Add(new Product() { ProductId = 1, Name = "apple", Price = 1.09 });
produkt.Add(new Product() { ProductId = 2, Name = "peach", Price = 1.57 });
produkt.Add(new Product() { ProductId = 3, Name = "banana", Price = 1.15 });
produkt.Add(new Product() { ProductId = 4, Name = "watermelon", Price = 4.50 });
produkt.Add(new Product() { ProductId = 5, Name = "melon", Price = 5.06 });
produkt.Add(new Product() { ProductId = 6, Name = "strawberries", Price = 6.99 });
produkt.Add(new Product() { ProductId = 7, Name = "raspberries", Price = 2.20 });
In your view you can create a drop down list like so:
#model ProductModel
#Html.DropDownListFor(n => n.MyProductId,
new SelectList(product, "ProductId", "Name"))
For more info you can have a look at this article
Give this a go :)
#model App.Models.Model
#Html.DropDownListFor(x => x.ProductId, new SelectList(Product, "Name", "Price"))
Related
Here is my previous post.
https://stackoverflow.com/questions/75106799/how-to-get-data-from-3-table-into-1-list/.
It works fine.
But i expect returning value as:
[{ "id": "1f5a6c7c-6168-4ac8-73a5-08daf474a373", "name": "Bag A", "quantity": 10, "category": "Cat-A" }, { "id": "9b8eb0cc-0da4-4b6a-73a6-08daf474a373", "name": "Shirt A", "quantity": 10, "category": "Cat-B" }, { "id": "DB2EE420-A4E5-407A-5F96-08DAF4759F9C", "name": "Shoes A", "quantity": 10, "category": "Cat-C" } ]
I use .net core 6 MVC - code first. Please help me.
I want to return value without "bag", "shirts","shoes". Look like
above:
Well, based on your question, you could achieve by introduing new model which would be containing all property that your "bag", "shirts","shoes" containing. Finally, you need to loop through the existing list item and bind those into new class/model. You can have a try in following way:
Create A new Model for generic List:
public class GenericClass
{
public int Id { get; set; }
public string Name { get; set; }
public int Quantity { get; set; }
public string Category { get; set; }
}
Note: We will use this model to loop over our existing list thus we would bind them into this.
Base Model:
public class GenericClass
{
public int Id { get; set; }
public string Name { get; set; }
public int Quantity { get; set; }
public string Category { get; set; }
}
public class Bags
{
public int Id { get; set; }
public string Name { get; set; }
public int Quantity { get; set; }
public string Category { get; set; }
}
public class Shirts
{
public int Id { get; set; }
public string Name { get; set; }
public int Quantity { get; set; }
public string Category { get; set; }
}
public class Shoes
{
public int Id { get; set; }
public string Name { get; set; }
public int Quantity { get; set; }
public string Category { get; set; }
}
Seed Data Into Model:
List<Bags> listBags = new List<Bags>();
listBags.Add(new Bags() { Id = 101, Name = "Bag A", Quantity = 10, Category = "Cat-A" });
listBags.Add(new Bags() { Id = 102, Name = "Bag B", Quantity = 15, Category = "Cat-A" });
listBags.Add(new Bags() { Id = 103, Name = "Bag C", Quantity = 20, Category = "Cat-A" });
List<Shirts> listShirts = new List<Shirts>();
listShirts.Add(new Shirts() { Id = 101, Name = "Shirt A", Quantity = 10, Category = "Cat-B" });
listShirts.Add(new Shirts() { Id = 102, Name = "Shirt B", Quantity = 15, Category = "Cat-B" });
listShirts.Add(new Shirts() { Id = 103, Name = "Shirt C", Quantity = 20, Category = "Cat-B" });
List<Shoes> listShoes = new List<Shoes>();
listShoes.Add(new Shoes() { Id = 101, Name = "Shirt A", Quantity = 10, Category = "Cat-S" });
listShoes.Add(new Shoes() { Id = 102, Name = "Shirt B", Quantity = 15, Category = "Cat-S" });
listShoes.Add(new Shoes() { Id = 103, Name = "Shirt C", Quantity = 20, Category = "Cat-S" });
Build Custom List:
var genericClass = new List<GenericClass>();
foreach (var item in listBags)
{
var bag = new GenericClass();
bag.Id = item.Id;
bag.Name = item.Name;
bag.Quantity = item.Quantity;
bag.Category = item.Category;
genericClass.Add(bag);
}
foreach (var item in listShirts)
{
var shirt = new GenericClass();
shirt.Id = item.Id;
shirt.Name = item.Name;
shirt.Quantity = item.Quantity;
shirt.Category = item.Category;
genericClass.Add(shirt);
}
foreach (var item in listShoes)
{
var shoes = new GenericClass();
shoes.Id = item.Id;
shoes.Name = item.Name;
shoes.Quantity = item.Quantity;
shoes.Category = item.Category;
genericClass.Add(shoes);
}
Complete Demo:
[HttpGet("GetFrom3TablesWithSameKey")]
public IActionResult GetFrom3TablesWithSameKey()
{
List<Bags> listBags = new List<Bags>();
listBags.Add(new Bags() { Id = 101, Name = "Bag A", Quantity = 10, Category = "Cat-A" });
listBags.Add(new Bags() { Id = 102, Name = "Bag B", Quantity = 15, Category = "Cat-A" });
listBags.Add(new Bags() { Id = 103, Name = "Bag C", Quantity = 20, Category = "Cat-A" });
List<Shirts> listShirts = new List<Shirts>();
listShirts.Add(new Shirts() { Id = 101, Name = "Shirt A", Quantity = 10, Category = "Cat-B" });
listShirts.Add(new Shirts() { Id = 102, Name = "Shirt B", Quantity = 15, Category = "Cat-B" });
listShirts.Add(new Shirts() { Id = 103, Name = "Shirt C", Quantity = 20, Category = "Cat-B" });
List<Shoes> listShoes = new List<Shoes>();
listShoes.Add(new Shoes() { Id = 101, Name = "Shirt A", Quantity = 10, Category = "Cat-S" });
listShoes.Add(new Shoes() { Id = 102, Name = "Shirt B", Quantity = 15, Category = "Cat-S" });
listShoes.Add(new Shoes() { Id = 103, Name = "Shirt C", Quantity = 20, Category = "Cat-S" });
var genericClass = new List<GenericClass>();
foreach (var item in listBags)
{
var bag = new GenericClass();
bag.Id = item.Id;
bag.Name = item.Name;
bag.Quantity = item.Quantity;
bag.Category = item.Category;
genericClass.Add(bag);
}
foreach (var item in listShirts)
{
var shirt = new GenericClass();
shirt.Id = item.Id;
shirt.Name = item.Name;
shirt.Quantity = item.Quantity;
shirt.Category = item.Category;
genericClass.Add(shirt);
}
foreach (var item in listShoes)
{
var shoes = new GenericClass();
shoes.Id = item.Id;
shoes.Name = item.Name;
shoes.Quantity = item.Quantity;
shoes.Category = item.Category;
genericClass.Add(shoes);
}
return Ok(genericClass);
}
Output:
Note: If you still have any concern please have a look on our official documnet here.
I have an EntityCollection which contains members coming from different Marketing Lists. Because a person can exist in various MarketingLists my EntityCollection can contain the same person multiple times.
To have this data initially grouped I do the following:
var groupedCustomerList = listMembers.Entities.GroupBy(u => u.Id).Select(grp => grp.ToList());
My EntityCollection contains also an Attribute called "priority" which leads to the following if the same person is found multiple times
Group_1
- Person_1 (priority 1)
Group_2
- Person_1 (priority 2)
- Person_2 (priority 1)
What I need to achieve is to remove the duplicate person(s) with the lower priority -> Person_1 in Group_2 needs to be removed.
What I have tried so far is:
foreach (var item in groupedCustomerList)
{
if (item.Count > 1)
{
// order the items in the group by priority set in the SelectionRow and take the first
// entry with the highest priority
var element = item.OrderBy(o => o.Attributes[AttributeNames.SelectionRow.SelectionRowPriority]).Take(1).ToList();
listMembersConsolidated.Add(element[0]);
}
else
{
listMembersConsolidated.Add(item[0]);
}
}
But this does not give me the desired result -> always the same person in the result
Does anybody have a hint for me?
Would be highly appreciated.
Thank you in advance.
I just created very simple console application in c# based on entity framework.
I created Product Entity and added around 15 products.
Then I added all these entity products in an Entity collection.
So that now I have almost same req as you need.
What I did is that keep only those Records in my entitycollection which have UnitsInStock highest among a Product ID.
For ex: For Product ID 1 I have only taken record with UnitsInStock =40
using System;
using System.Collections.Generic;
using System.Data.Entity.Core.Objects.DataClasses;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EntityCollectionTesting
{
class Program
{
static void Main(string[] args)
{
var productList =
new List<Product> {
new Product { ProductID = 1, ProductName = "Chai", Category = "Beverages", UnitPrice = 18.0000M, UnitsInStock = 39 },
new Product { ProductID = 2, ProductName = "Chang", Category = "Beverages", UnitPrice = 19.0000M, UnitsInStock = 17 },
new Product { ProductID = 3, ProductName = "Aniseed Syrup", Category = "Condiments", UnitPrice = 10.0000M, UnitsInStock = 13 },
new Product { ProductID = 4, ProductName = "Chef Anton's Cajun Seasoning", Category = "Condiments", UnitPrice = 22.0000M, UnitsInStock = 53 },
new Product { ProductID = 5, ProductName = "Chef Anton's Gumbo Mix", Category = "Condiments", UnitPrice = 21.3500M, UnitsInStock = 0 },
new Product { ProductID = 6, ProductName = "Grandma's Boysenberry Spread", Category = "Condiments", UnitPrice = 25.0000M, UnitsInStock = 120 },
new Product { ProductID = 7, ProductName = "Uncle Bob's Organic Dried Pears", Category = "Produce", UnitPrice = 30.0000M, UnitsInStock = 15 },
new Product { ProductID = 8, ProductName = "Northwoods Cranberry Sauce", Category = "Condiments", UnitPrice = 40.0000M, UnitsInStock = 6 },
new Product { ProductID = 9, ProductName = "Mishi Kobe Niku", Category = "Meat/Poultry", UnitPrice = 97.0000M, UnitsInStock = 29 },
new Product { ProductID = 10, ProductName = "Ikura", Category = "Seafood", UnitPrice = 31.0000M, UnitsInStock = 31 },
new Product { ProductID = 1, ProductName = "Ikura", Category = "Seafood", UnitPrice = 31.0000M, UnitsInStock = 40 },
new Product { ProductID = 2, ProductName = "Ikura", Category = "Seafood", UnitPrice = 31.0000M, UnitsInStock = 56 },
new Product { ProductID = 3, ProductName = "Ikura", Category = "Seafood", UnitPrice = 31.0000M, UnitsInStock = 11 },
new Product { ProductID = 4, ProductName = "Ikura", Category = "Seafood", UnitPrice = 31.0000M, UnitsInStock = 12 },
new Product { ProductID = 5, ProductName = "Ikura", Category = "Seafood", UnitPrice = 31.0000M, UnitsInStock = 1 }
};
EntityCollection<Product> entityCollection = new EntityCollection<Product>();
EntityCollection<Product> newCollection = new EntityCollection<Product>();
foreach (var VARIABLE in productList)
{
entityCollection.Add(VARIABLE);
newCollection.Add(VARIABLE);
}
foreach (var ec in entityCollection)
{
foreach (var nc in newCollection)
{
if (ec.ProductID == nc.ProductID)
{
if (ec.UnitsInStock > nc.UnitsInStock)
{
newCollection.Remove(nc);
break;
}
}
}
}
foreach (var VARIABLE in newCollection)
{
Console.WriteLine($"{VARIABLE.ProductID} and {VARIABLE.UnitsInStock}");
}
Console.ReadLine();
}
}
public class Product
{
public int ProductID { get; set; }
public string ProductName { get; set; }
public string Category { get; set; }
public decimal UnitPrice { get; set; }
public int UnitsInStock { get; set; }
}
}
You can try this. I've used sample list but you can apply with your entity collection. Enjoy coding
List<Employee> employees = new List<Employee>();
var newEmployeList = employees.Distinct().ToList();
I am implementing a Hierarchy Grid in ASP.Net MVC using syncfusion Grid Control.
I am fetching the data from server side with an ajax call on the expansion of child grid. When i try to expand child grid, the ajax call fetches the data in JSON format and a JavaScript error (TypeError: this.model.currentViewData is undefined) occurs and data in the child grid doesn't load into child grid.
Details of Question and running source code example are also available here.
Classes
public class Data
{
public int OrderID { get; set; }
public int EmployeeID { get; set; }
public string ShipCountry { get; set; }
public List<ChildData> Employee { get; set; }
}
public class ChildData
{
public int EmployeeID { get; set; }
public string FirstNAme { get; set; }
public string LastNAme { get; set; }
}
Controller
public class GridController : Controller
{
//
// GET: /Grid/
List<Data> obj = new List<Data>();
public ActionResult GridFeatures()
{
var DataSource = GetData();
ViewBag.datasource = DataSource.ToList();
return View();
}
public JsonResult GetChildData(int _empID)
{
var ChildDaqtaSource = ChildData(_empID);
return Json(ChildDaqtaSource, JsonRequestBehavior.AllowGet);
}
public static List<Data> GetData()
{
List<Data> obj = new List<Data>();
//obj.Add(new Data() { OrderID = 1000, EmployeeID = 1, ShipCountry = "india", Employee = new List<ChildData>() { new ChildData() { EmployeeID = 1, FirstNAme = "Janet", LastNAme = "David" } } });
//obj.Add(new Data() { OrderID = 1001, EmployeeID = 2, ShipCountry = "France", Employee = new List<ChildData>() { new ChildData() { EmployeeID = 2, FirstNAme = "Nancy", LastNAme = "John" } } });
//obj.Add(new Data() { OrderID = 1002, EmployeeID = 3, ShipCountry = "US", Employee = new List<ChildData>() { new ChildData() { EmployeeID = 3, FirstNAme = "David", LastNAme = "Staven" } } });
//obj.Add(new Data() { OrderID = 1003, EmployeeID = 4, ShipCountry = "US", Employee = new List<ChildData>() { new ChildData() { EmployeeID = 4, FirstNAme = "Janet", LastNAme = "David" } } });
obj.Add(new Data() { OrderID = 1000, EmployeeID = 1, ShipCountry = "india" });
obj.Add(new Data() { OrderID = 1001, EmployeeID = 2, ShipCountry = "France" });
obj.Add(new Data() { OrderID = 1002, EmployeeID = 3, ShipCountry = "US" });
obj.Add(new Data() { OrderID = 1003, EmployeeID = 4, ShipCountry = "US" });
return obj;
}
public static List<ChildData> ChildData(int _EmpID)
{
List<ChildData> _childData = new List<ChildData>();
_childData.Add(new ChildData { EmployeeID = 1, FirstNAme = "John", LastNAme = "Freeman" });
_childData.Add(new ChildData { EmployeeID = 1, FirstNAme = "steve", LastNAme = "Alexander" });
_childData.Add(new ChildData { EmployeeID = 1, FirstNAme = "Ali", LastNAme = "Naeem" });
_childData.Add(new ChildData { EmployeeID = 1, FirstNAme = "Alex", LastNAme = "Wonder" });
_childData.Add(new ChildData { EmployeeID = 1, FirstNAme = "Bill", LastNAme = "Gates" });
_childData.Add(new ChildData { EmployeeID = 1, FirstNAme = "Alan", LastNAme = "Turing" });
_childData.Add(new ChildData { EmployeeID = 2, FirstNAme = "Mark", LastNAme = "Anthoney" });
_childData.Add(new ChildData { EmployeeID = 2, FirstNAme = "Carl", LastNAme = "Shoemaker" });
_childData.Add(new ChildData { EmployeeID = 3, FirstNAme = "Carlos", LastNAme = "Anthony" });
return _childData.Where(x => x.EmployeeID == _EmpID).ToList();
}
}
Razor View (GridFeatures.cshtml)
#model List<RemoteSaveAdaptorSample.Controllers.Data>
<h2>Requisitions</h2>
#(Html.EJ().Grid<RemoteSaveAdaptorSample.Controllers.Data>("EmployeeGrid")
.Datasource((List<RemoteSaveAdaptorSample.Controllers.Data>)ViewBag.DataSource)
//.Datasource(Model)
.AllowSorting(true)
.AllowResizing(true)
.AllowPaging(true)
.AllowGrouping(true)
.AllowTextWrap(true)
.AllowScrolling(true)
.AllowFiltering()
.EnableRowHover(true)
.Columns(col =>
{
col.Field(x => x.EmployeeID).HeaderText("EmployeeID").Width(30).IsPrimaryKey(true).AllowResizing(false).Add();
col.Field(x => x.OrderID).HeaderText("OrderID").Width(60).AllowFiltering(true).Add();
col.Field(x => x.ShipCountry).HeaderText("Country").Width(100).Add();
})
.ChildGrid
//<RemoteSaveAdaptorSample.Controllers.ChildData>
(_childGrid =>
{
_childGrid
.QueryString("EmployeeID")
.AllowPaging()
.Columns(_childCol =>
{
_childCol.Field("EmployeeID").HeaderText("EmployeeID").Add();
_childCol.Field("FirstNAme").HeaderText("First Name").Add();
})
.ClientSideEvents(x => x.Load("loadEvent"))
;
})
)
<script type="text/javascript">
function loadEvent(args) {
var data = this.model.parentDetails.parentKeyFieldValue;
this.model.dataSource = ej.DataManager({
url: "/grid/GetChildData?_empID=" + data + ""
, adaptor: "UrlAdaptor"
});
}
</script>
Any help is appriciated
Thanx
I have checked the query and found that you have returned the result alone from server side instead of passing it as result and count pair. When using UrlAdaptor it is must to return the data as result and count pair. So that it will bind the data to the grid.
Refer the code example
public JsonResult GetChildData(int _empID)
{
var ChildDaqtaSource = ChildData(_empID);
var count = ChildDaqtaSource.Count;
return Json(new { result = ChildDaqtaSource, count = count });
}
Refer the documentation link of UrlAdaptor
Link: https://help.syncfusion.com/aspnetmvc/grid/data-adaptors#url-adaptor
i have 2 tables in a database
supplier table: SupplierID - SupplierName
product table: ProductID - ProductName - UnitsInStock - SupplierID
how can i select the supplier that has largest UnitsInStock?
here's the code i have
private storeDBEntities2 db1 = new storeDBEntities2();
public ActionResult Index()
{
var product = db1.Products.Where(e => e.UnitsInStock == 0);
var largestSupplier = db1.Products.GroupBy(e => e.SupplierID);
Product minimord = db1.Products.OrderBy(e => e.UnitsOnOrder).FirstOrDefault();
var supplier = // this is the query i am struggling with
AllModelsProduct all = new AllModelsProduct { Iproduct = product.ToList(), product = new Product(),largestSupplierOfTheStore = supplier,minimumOrders = minimord };
return View(all);
}
here's a picture of my data
i need to get supplierID 345 as we have 20 units belong to him in store which is greater than the other supplier with 5 + 3 + 0 = 8 units
If all you're looking to do is find the supplier with the largest number of UnitsInStock then this should do the trick.
I have created a dotNetFiddle for you to observe.
But here it is anyway:
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
List<Supply> lstSuppliers = new List<Supply>();
Supply supply1 = new Supply() { ID = 1, SupplierName = "Supplier One"};
Supply supply2 = new Supply() { ID = 2, SupplierName = "Supplier Two"};
lstSuppliers.Add(supply1);
lstSuppliers.Add(supply2);
Product product1 = new Product() {ID = 1, UnitsInStock = 3, SupplierID = 1};
Product product2 = new Product() {ID = 2, UnitsInStock = 3, SupplierID = 2};
Product product3 = new Product() {ID = 3, UnitsInStock = 5, SupplierID = 1};
List<Product> lstAllProducts = new List<Product>();
lstAllProducts.Add(product1);
lstAllProducts.Add(product2);
lstAllProducts.Add(product3);
var findSupplierId = lstAllProducts.GroupBy(x => x.SupplierID).Select(x => new{ Supplier = x.Key.ToString(), Count = x.Sum(g => g.UnitsInStock)}).OrderByDescending(x => x.Count).First().Supplier;
Console.WriteLine(findSupplierId);
Console.WriteLine(lstSuppliers.Single(x => x.ID.ToString() == findSupplierId).SupplierName);
}
}
public class Supply{
public int ID {get;set;}
public string SupplierName {get;set;}
}
public class Product{
public int ID {get;set;}
public int UnitsInStock {get;set;}
public int SupplierID {get;set;}
}
This uses the GroupBy, along with creating anonymous classes to get the desired outcome.
Let me know if this helps!
Update - To show if multiple suppliers have the same units in stock
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
List<Supply> lstSuppliers = new List<Supply>();
Supply supply1 = new Supply() { ID = 1, SupplierName = "Supplier One"};
Supply supply2 = new Supply() { ID = 2, SupplierName = "Supplier Two"};
Supply supply3 = new Supply() { ID = 3, SupplierName = "Supplier Three"};
lstSuppliers.Add(supply1);
lstSuppliers.Add(supply2);
lstSuppliers.Add(supply3);
Product product1 = new Product() {ID = 1, UnitsInStock = 3, SupplierID = 1};
Product product2 = new Product() {ID = 2, UnitsInStock = 3, SupplierID = 2};
Product product3 = new Product() {ID = 3, UnitsInStock = 5, SupplierID = 1};
Product product4 = new Product() {ID = 4, UnitsInStock = 8, SupplierID = 3};
List<Product> lstAllProducts = new List<Product>();
lstAllProducts.Add(product1);
lstAllProducts.Add(product2);
lstAllProducts.Add(product3);
lstAllProducts.Add(product4);
// finds largest supplier
//var findSupplierId = lstAllProducts.GroupBy(x => x.SupplierID).Select(x => new{ Supplier = x.Key.ToString(), Count = x.Sum(g => g.UnitsInStock)}).OrderByDescending(x => x.Count).First().Supplier;
//Console.WriteLine(lstSuppliers.Single(x => x.ID.ToString() == findSupplierId).SupplierName);
// What if there are multiple suppliers with the same number of units in stock?
// first - we have to find the largest number of units in stock
var findLargestNumberUIS = lstAllProducts.GroupBy(x => x.SupplierID).Select(x => new{ Supplier = x.Key.ToString(), Count = x.Sum(g => g.UnitsInStock)}).Max(x => x.Count); // 8
// second - gather a list of suppliers where their units in stock == findLargestNumberUIS
var lstOfLargestSuppliers = lstAllProducts.GroupBy(x => x.SupplierID).Select(x => new{ Supplier = x.Key.ToString(), Count = x.Sum(g => g.UnitsInStock)}).Where(x => x.Count == findLargestNumberUIS).ToList();
// third - loop through lstOfLargestSuppliers to get all suppliers that have the same amount of units in stock which happen to be the largest
foreach(var item in lstOfLargestSuppliers){
var supplier = lstSuppliers.Single(x => x.ID.ToString() == item.Supplier).SupplierName;
Console.WriteLine(supplier); // print the supplier names to console
// Output - Supplier One
// Supplier Three
}
}
}
public class Supply{
public int ID {get;set;}
public string SupplierName {get;set;}
}
public class Product{
public int ID {get;set;}
public int UnitsInStock {get;set;}
public int SupplierID {get;set;}
}
I'm trying to order by an attribute of a related object. Just an example, this is the situation. I have this two classes:
public class Publication
{
public int Id { get; set; }
public string Name { get; set; }
public List<Product> Products { get; set; }
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public int PublicationId { get; set; }
[ForeignKey("PublicationId")]
public Publication Publication { get; set; }
public int Category { get;set; }
}
Now I need to get all the Publications with Product's Category = 1 and ordered by Publication Id desc:
IQueryable<Publication> query = db.Publications.Where("Products.Any(Category = 1)");
List<Publication> list = query.OrderBy("Id desc").ToList();
This is working great! But... How can I order Publications by Product's category (desc or asc) using Dynamic Linq?
I haven't found how to do it using System.Linq.Dynamic but as for Linq this works
var query = publications.OrderByDescending(p => p.Products.Select(x => x.Category).FirstOrDefault()).ToList();
Here is the test class:
var publications = new List<Publication>
{
new Publication
{
Products = new List<Product>
{
new Product {Category = 5},
new Product {Category = 6},
new Product {Category = 7}
}
},
new Publication
{
Products = new List<Product>
{
new Product {Category = 2},
new Product {Category = 3},
new Product {Category = 4}
}
},
new Publication
{
Products = new List<Product>
{
new Product {Category = 8},
new Product {Category = 9},
new Product {Category = 10}
}
}
};
var query = publications.OrderByDescending(p => p.Products.Select(x => x.Category).FirstOrDefault()).ToList();
query.ForEach(x => Console.WriteLine(x.ToString()));
The output was:
8 , 9 , 10
5 , 6 , 7
2 , 3 , 4
As you see it doesn't internally order the Products.