I want to query the database and get a sport object containing all inner lists, but for some reason I'm missing, the select only goes 2 levels deep in lists, any deepers and the lists property have a value of null,
example of the structure
public class Sports
{
public int id { get; set; }
public string name { get; set; }
public List<League> leagues { get; set; }
}
public class League
{
public int id { get; set; }
public string name { get; set; }
public string description { get; set; }
public List<Team> teams { get; set; }
}
public class Team
{
public int id { get; set; }
public string name { get; set; }
public string successrate { get; set; }
public List<Player> players { get; set; }
}
public class Player
{
public int id { get; set; }
public string name { get; set; }
public int age { get; set; }
}
I created property in MyAppContext file as this
public DbSet<Sports> sports { get; set; }
now when I call an item using select or linq or any other way I tried, the sport object is always 2 Dimensional, meaning it doesn't go deeper than two levels in nested lists! Example of result using var sport=db.Sports.First() the result is {"id":1,"name":"Football","leagues":null} or if I used select()
var sportQuery = db.sports.Select(
s=>new Sports(){
id=s.id,
leagues=s.leagues,
name=s.name
}).First();
I still don't get full information {"id":1,"name":"Football","leagues":[{"id":1,"name":"fc","description":"Some Leauge","teams":null},{"id":2,"name":"al","description":"League","teams":null}]}
why is that! and how to get full object like this
{"id":1,"name":"Football","leagues":[{"id":1,"name":"fc","description":"Some Leauge","teams":[{"id":1,"name":"real madrid","successrate":null,"players":[{"id":1,"name":"Cristiano Ronaldo","age":21},{"id":2,"name":"Iniesta","age":38}]},{"id":2,"name":"Barcelona","successrate":null,"players":[{"id":1,"name":"Cristiano Ronaldo","age":21},{"id":2,"name":"Iniesta","age":38}]}]},{"id":2,"name":"al","description":"League","teams":[{"id":1,"name":"real madrid","successrate":null,"players":[{"id":1,"name":"Cristiano Ronaldo","age":21},{"id":2,"name":"Iniesta","age":38}]},{"id":2,"name":"Barcelona","successrate":null,"players":[{"id":1,"name":"Cristiano Ronaldo","age":21},{"id":2,"name":"Iniesta","age":38}]}]}]}
I've been stuck for days, Please any help would be much appreciated
Try following :
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
DataBase db = new DataBase();
var sportQuery = db.sports.Select(s=> s.leagues.Select(l => l.teams.Select(t => t.players.Select(p => new {
playerid = p.id,
playerName = p.name,
playerAge = p.age,
teamId = t.id,
teamName = t.name,
teamSucessrate = t.successrate,
leagueId= l.id,
leagueName= l.name,
leagueDescription = l.description,
sportId = s.id,
sportName = s.name
}))
.SelectMany(p => p))
.SelectMany(t => t))
.SelectMany(l => l)
.ToList();
}
}
public class DataBase
{
public List<Sports> sports { get; set;}
}
public class Sports
{
public int id { get; set; }
public string name { get; set; }
public List<League> leagues { get; set; }
}
public class League
{
public int id { get; set; }
public string name { get; set; }
public string description { get; set; }
public List<Team> teams { get; set; }
}
public class Team
{
public int id { get; set; }
public string name { get; set; }
public string successrate { get; set; }
public List<Player> players { get; set; }
}
public class Player
{
public int id { get; set; }
public string name { get; set; }
public int age { get; set; }
}
}
problem solved using Include() and thenInclude()
https://learn.microsoft.com/en-us/ef/core/querying/related-data
however, that doesn't explain why Select() only loads one list property deep, also it seems like i should be able to load object with select only or linq
I have a class CategoryModel in c#, which is an element of a tree:
public class CategoryModel
{
public string Id { get; set; }
public string Name { get; set; }
public string NameEng { get; set; }
public string ParentCategoryId { get; set; }
public ICollection<string> ChildCategoriesIds { get; set; } = new List<string>();
public ICollection<string> ProductsIds { get; set; } = new List<string>();
}
public class Product
{
public string Id { get; set; }
public string Name { get; set; }
public string NameEng { get; set; }
}
The ChildCategoriesIds contains Id class CategoryModel.
The ProductsIds contains Id class Product.
How proccesed data in new classes:
public class CategoryNew
{
public string Uid { get; set; }
public string Name { get; set; }
public string NameEng { get; set; }
public bool? IsDeleted { get; set; }
public IEnumerable<UidName> ChildCategories { get; set; } = new List<UidName>();
public IEnumerable<UidName> Products { get; set; } = new List<UidName>();
}
public class UidName
{
public string Uid { get; set; }
public string Name { get; set; }
public string NameEng { get; set; }
public bool? IsDeleted { get; set; }
}
You can specify own constructor for CategoryNew, which will take as an argument object of class CategoryModel, in which you will set all properties of CategoryNew based on values of properties of CategoryModel:
public CategoryNew(CategoryModel cm){
// set properties
}
Then your method would be:
public List<CategoryNew> ConverModelToNew(List<CategoryModel> lstCatModel){
List<CategoryNew> lstCatNew = new List<CategoryNew>();
foreach(var item in lstCatModel){
lstCatNew.Add(new CetagoryNew(item));
}
return lstCatNew;
}
Assuming you are trying to convert one set of object to another set of objects.
First of all, I believe categories shouldl inherit UidName so you will memory more efficiently by reducing duplicate objects.
public class CategoryNew: UidName
{
public IEnumerable<CategoryNew> ChildCategories { get; set; } = new List<CategoryNew>();
public IEnumerable<UidName> Products { get; set; } = new List<UidName>();
}
public class UidName
{
public string Uid { get; set; }
public string Name { get; set; }
public string NameEng { get; set; }
public bool? IsDeleted { get; set; }
}
// first run to create products
var newProducts = products.Select(p => new UidName {
Uid = p.Id,
Name = p.Name,
NameEnd = p.NameEng
}).ToArray();
// second run to create categories with products
var newCategories = categories.Select(c => new CategoryNew {
Uid = c.Id,
Name = c.Name,
NameEng = c.NameEng,
IsDeleted = (bool?)null, //TODO
Products = newProducts.Where(p => c.ProductIds.Contains(p.Uid))
.ToList()
}).ToArray();
// last run find sub categories
foreach(var category in newCategories) {
var oldCategory = categories.First(c => c.Id == category.Uid);
category.ChildCategories = newCategories.Where(c => oldCategory.ChildCategoriesIds.Contains(c.Uid))
.ToArray();
}
My question is about how can i select some one-two column from those tables are included and at the end when i am selecting as list it is returning list of parent object but child are contain those column i mention to select?
var testq = _db.Homes
.Include(x => x.Indexs.Cities.Proviences.Regions)
.Include(x => x.Images)
.Select(x => new Homes {
Images = x.Images,
Address = x.Address,
Indexs.Cities.Proviences.Regions =
x.Indexs.Cities.Proviences.Regions.Name });
At the end I need to have list of home model (List) and just images and Address and region name have value and important just those are selected from database not all infromation in the tables. I am trying to make a query with better performance
Edit Add Models
public partial class dbContext : DbContext
{
public virtual DbSet<City> Cities { get; set; }
public virtual DbSet<Province> Provinces { get; set; }
public virtual DbSet<Region> Regions { get; set; }
public virtual DbSet<Index> Indexs { get; set; }
public virtual DbSet<Home> Homes { get; set; }
public virtual DbSet<Images> Imageses { get; set; }
}
public partial class Home
{
public Home()
{
Imageses = new HashSet<Images>();
}
[Key]
public int IDHome { get; set; }
[Required]
[StringLength(5)]
public string Cap { get; set; }
[Required]
[StringLength(10)]
public string Number { get; set; }
[Required]
[StringLength(50)]
public string Address { get; set; }
....
public virtual Index Indexs { get; set; }
public virtual ICollection<Images> Imageses { get; set; }
}
public class Index
{
public int ID { get; set; }
public int IDHome { get; set; }
....
public virtual City Cities { get; set; }
}
public partial class City
{
[Key]
public int ID { get; set; }
public int IDProvincia { get; set; }
public decimal Latitudine { get; set; }
public decimal Longitudine { get; set; }
[Required]
[StringLength(100)]
public string Name { get; set; }
....
public virtual Province Provinces { get; set; }
}
public partial class Province
{
[Key]
public int ID { get; set; }
public int IDRegione { get; set; }
[Required]
[StringLength(50)]
public string Name { get; set; }
[Required]
[StringLength(3)]
public string Init { get; set; }
...
public virtual Region Regions { get; set; }
}
public partial class Region
{
[Key]
public int ID { get; set; }
[Required]
[StringLength(50)]
public string Name { get; set; }
public DateTime DataInsert { get; set; }
...
}
public class Images
{
public int ID { get; set; }
public string Path { get; set; }
...
}
absolutely tables have more column just add here as example
you have to define a new type with the fields you need, or use an anonymous type.
.Select(x => new {
Images = x.Images,
Address = x.Address,
Indexs.Cities.Proviences.Regions =
x.Indexs.Cities.Proviences.Regions.Name });
I stored the objects of the following classes in a ravendb database:
public class Continent
{
public string Name { get; set; }
public List<Country> Countries{ get; set; }
}
public class Countries
{
public string Name { get; set; }
public List<Province> Provinces{ get; set; }
}
public class Province
{
public string Name { get; set; }
public List<Province> Cities { get; set; }
}
public class City
{
public string Name { get; set; }
public string Address { get; set; }
}
Thanks to a post (RavenDB: how to retrieve the top nodes in a nested collection?) I have learned how to use session.Query to retrieve from the database all the continents having cities with Name and Address respectively set to "aloma" and "123". I would like to write the same query using session.Advanced.DocumentQuery. So can you please tell me how to transform the following query into a session.Advanced.DocumentQuery: var continents = session.Query() .Where(x=>x.Countries.Any(country => country.Provinces.Any(p=>p.Cities.Any(city => city.Name == "123" && city.Address == "aloma"))).OfType().ToList(); ?
Note, this is probably not the best way to do this but it's the only way I know how. Also, note the following will create an index once executed.
var results = session.Advanced.DocumentQuery<Continent>().Where("Countries,Provinces,Cities,Name: 123 AND Countries,Provinces,Cities,Address: aloma").ToList();
Model structure used:
public class Continent
{
public string Id { get; set; }
public string Name { get; set; }
public List<Country> Countries { get; set; }
}
public class Country
{
public string Name { get; set; }
public List<Province> Provinces { get; set; }
}
public class Province
{
public string Name { get; set; }
public List<City> Cities { get; set; }
}
public class City
{
public string Name { get; set; }
public string Address { get; set; }
}
I have two classes that partake in a parent-child relationship. The parent class is Country, and the child class is City:
public partial class Country
{
public Country()
{
this.Cities = new List<City>();
}
public int Id { get; set; }
public string Name { get; set; }
public string AlphaCodeTwo { get; set; }
public string AlphaCodeThree { get; set; }
public Nullable<int> NumericCode { get; set; }
public string Capital { get; set; }
public string Nationality { get; set; }
public Nullable<decimal> CapitalArea { get; set; }
public Nullable<decimal> CapitalPopulation { get; set; }
public string Image { get; set; }
public virtual List<City> Cities { get; set; }
}
public partial class City
{
public int Id { get; set; }
public string Name { get; set; }
public string Code { get; set; }
public Nullable<int> NumericCode { get; set; }
public virtual Country Country { get; set; }
}
When I select a City object with the following LINQ query, the navigation property to the parent class is null:
private List<Country> _Country;
var City = _Country.SelectMany(c => c.Cities).OrderBy(ci => ci.Name).ToList();
I get all children, but no parent data.
If you're using Entity Framework, you can use .Include() to grab the navigation property data as you load the objects. Note that it tends to produce some pretty gnarly queries.
var city = (
from c in db.Cities.Include(c => c.Country)
where c.CountryId == CountryId
orderby c.Name
select c
).ToList();