I want a lambda expression, that when i call a Company from database with id 1030 to bring me Companys info, a list with all the cars that company has and a list of all images that related to each car (each car has 4 images).
Structure of my classes:
public partial class Companies
{
public int CompanyId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Tel { get; set; }
public string Logo { get; set; }
public int? Owner { get; set; }
public int? Address { get; set; }
public int? Publish { get; set; }
public ICollection<Cars> Cars { get; set; }
}
public partial class Cars
{
public int CarId { get; set; }
public string Manufacturer { get; set; }
public string Model { get; set; }
public string Year { get; set; }
public string Description { get; set; }
public decimal? Price { get; set; }
public int? CarCatId { get; set; }
public int? CompanyId { get; set; }
public int? CharacteristicId { get; set; }
public ICollection<CarImages> CarImages { get; set; }
}
public partial class CarImages
{
public int CarImagesId { get; set; }
public string Image { get; set; }
public int? CarId { get; set; }
public Cars Car { get; set; }
}
As you can see in Company class, I have a reference to Cars class as ICollection, and the same thing in Cars class with CarImages.
I've try lot of things including those:
var compInfo = _context.Companies.SelectMany(cr => cr.Cars.SelectMany(i =>i.CarImages.Where(car => car.CarId == car.Car.CarId))).ToList();
var compInfo2 = _context.Companies.Include(a => a.AddressNavigation).Include(cr =>cr.Cars.).FirstOrDefault(c => c.CompanyId == id);
The 2nd brings me the info of company (and it's address) and the list of the cars (which is the half success) but not the images..
The 1st just brings me a list all the info of images table.
I found the solution.
//Get the Company with id == 1030.
var x = _context.Companies.Include(a => a.AddressNavigation).Include(c => c.Cars).Where(c => c.CompanyId == id).FirstOrDefault();
//Get the Car ICollection and include the CarImages ICollection depending on CompanyID.
var y = _context.Cars.Include(img => img.CarImages).Where(cr => cr.CompanyId == x.CompanyId).ToList();
//Now each Car in our Cars list has a list of CarImages related to each car. Finaly pass our data to our Company var(x) and send it to View.
x.Cars = y;
return View(x);
Related
My scenario: Users will be able to create lists and add items to these lists. What I want to do is to find the items in the lists created by the users at most.
Item Entity
public class Item:BaseEntity
{
public string Name { get; set; }
public decimal Price { get; set; }
public decimal DiscountedPrice{ get; set; }
public virtual ICollection<ItemList> ItemLists { get; set; }
}
Item List Entity
public class ItemList:BaseEntity
{
public string Name { get; set; }
public string Description { get; set; }
public int UserId { get; set; }
public ICollection<Item> Items { get; set; }
[ForeignKey("UserId")]
public virtual User User { get; set; }
}
User Entity
public class User:BaseEntity
{
public string Name { get; set; }
public string Surname { get; set; }
public string Gsm { get; set; }
public string Email { get; set; }
public virtual ICollection<ItemList> ItemLists{ get; set; }
}
my DTO
public class TopItemsForUsers
{
[BsonRepresentation(BsonType.ObjectId)]
[BsonId]
public string ItemId { get; set; }
public string UserId { get; set; }
public int Quantity { get; set; }
}
My Item repository
var query = _context.Items.Include(l => l.ItemLists)
.GroupBy(g => g.ItemLists)
.Select(z => new TopItemsInLists { ItemId = z.Key.ToString(), Quantity = z.Count() })
.OrderByDescending(z => z.Quantity)
.Take(10);
I want to get products that are very present in users' lists
Where am I doing wrong? If anyone has any other suggestions
Try this query. I hope I understand question correctly.
var query =
from u in _context.Users
from il in u.ItemLists
from i in il.Items
group i by new { UserId = u.Id, ItemId = i.Id } into g
select new TopItemsInLists
{
UserId = g.Key.UserId.ToString(),
ItemId = g.Key.ItemId.ToString(),
Quantity = g.Count()
};
query = query
.OrderByDescending(z => z.Quantity)
.Take(10);
I'm trying to bring a listing to frontEnd.
I'm using mongoDb. My mongodb has a colletion called Employee. Employee has the following attribute
public class EmployeeViewModel
{
[BsonId(IdGenerator = typeof(StringObjectIdGenerator))]
public string ownerId { get; set; }
public string atributeChange { get; set; }
public PersonalDataViewModel personalData { get; set; }
public AddressViewModel address { get; set; }
public List<EmailsViewModel> emails { get; set; }
public SyndicateViewModel syndicate { get; set; }
public List<DependentsViewModel> dependents { get; set; }
public List<PhoneViewModel> phone { get; set; }
public List<BankViewModel> bank { get; set; }
public AttributesViewModel attributes { get; set; }
public List<BenefitsViewModel> benefits { get; set; }
public TransportViewModel transport { get; set; }
public List<AttachmentsViewModel> attachments { get; set; }
public List<DocumentsViewModel> documents { get; set; }
public List<DocumentsImagesViewModel> DependentsDocuments { get; set; }
public List<AttachmentsViewModel> DependentsAttachments { get; set; }
public List<BenefitsViewModel> DependentsBenefits { get; set; }
}
In this Model, I have an attribute called: public List <DocumentsImagesViewModel> DependentsDocuments {get; set; }:
public class DocumentsViewModel
{
[BsonId]
public string ownerId { get; set; }
public string id { get; set; }
public string dependentId { get; set; }
public string number { get; set; }
public DateTime expiration { get; set; }
public List<DocumentsImagesViewModel> images { get; set; }
public List<DocumentPropertiesViewModel> properties { get; set; }
public DocumentTypeViewModel type { get; set; }
}
I'm trying to bring benefits that contain the depedentID equal of the parameter. When I use this method, it has an error that can not be converted. IEnumerable to List C #
public async Task<List<Documents>> GetDocument(string ownerId, string dependentId)
{
var query = from employee in _employee.AsQueryable()
where employee.ownerId == ownerId
select new Employee()
{
DependentsDocuments = employee.DependentsDocuments.Where(x => x.dependentId == dependentId)
};
return query.ToList();
}
What is the best way to get this data? this filter?
I used this question as a reference: Mongodb C# driver return only matching sub documents in array
LINQ's .Where returns IEnumerable<T>, your model expects a List<T>, you can either change your model to IEnumerable<T> or you can change this line of code:
DependentsDocuments = employee.DependentsDocuments
.Where(x => x.dependentId == dependentId)
to this:
DependentsDocuments = employee.DependentsDocuments
.Where(x => x.dependentId == dependentId)
.ToList()
changing your code to this one maybe it work:
public async Task<List<Documents>> GetDocument(string ownerId, string dependentId)
{
var query = (from employee in _employee.AsQueryable()
where employee.ownerId == ownerId
select new Employee()
{
DependentsDocuments = employee.DependentsDocuments.Where(x => x.dependentId == dependentId).ToList()
}).ToList();
return query.ToList();
}
I am getting confused with my LINQ query and wondering if there is a way I can achieve the following:
A user has a list of liked Categories:
public class ApplicationUser : IdentityUser
{
[PersonalData]
public string Name { get; set; }
[PersonalData]
[DataType(DataType.Date)]
public DateTime DOB { get; set; }
[PersonalData]
public PersonGender Gender { get; set; }
[PersonalData]
[ForeignKey("Suburb")]
public int SuburbId { get; set; }
//Information about user preferences
public ICollection<UserCategory> LikedCategories { get; set; }
public virtual Suburb Suburb { get; set; }
}
Where UserCategory is defined as follows:
public class UserCategory
{
[Key]
public int Id { get; set; }
public ApplicationUser applicationUser { get; set; }
public Category Category { get; set; }
[ForeignKey("ApplicationUser")]
public string applicationUserId { get; set; }
[ForeignKey("Category")]
public int CategoryId { get; set; }
}
And Category is:
public class Category
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
public int CategoryFollowers { get; set; }
public ICollection<EventCategory> EventCategories { get; set; }
public ICollection<UserCategory> UserCategories { get; set; }
}
}
Finally, in my Events class I have the following:
public class Event
{
[Key]
public int ID { get; set; }
[Required]
public string Name { get; set; }
[Display(Name = "Is Featured?")]
public bool isFeatured { get; set; }
public byte[] EventImage1 { get; set; }
public byte[] EventImage2 { get; set; }
public virtual ICollection<EventCategory> EventCategories { get; set; }
public virtual ICollection<UserEvent> UserEvents { get; set; }
My view requires an object of type Event, so I am trying to return a list of Events where the EventCategory is contained in the UserCategory table. In other words I just want to show events that the user has liked the category for.
MORE CLARIFICATION
I am able to filter my events by category from a different function that takes in a hardcoded category Id from the view and this works fine:
//GET:// Browse event by category
public async Task<IActionResult> BrowseByCategory(int? id, int? alt_id)
{
if (id == null)
{
return NotFound();
}
var eventsContext = _context.Events
.Include(m => m.Venue)
.ThenInclude(mf => mf.Suburb)
.ThenInclude(mc => mc.Constituency)
.ThenInclude(md => md.City)
.Where(e => e.EventCategories.Any(c => c.Category.ID == id || c.Category.ID == alt_id))
.Take(15)
.OrderByDescending(o => o.StartDate);
return View("Browse",await eventsContext.ToListAsync());
}
I would like to do the exact same as above, but rather than pass in the hardcoded ID queries from the form, I want the query to check the categoryIDs that are saved in the UserCategory table. There is no set number of how many UserCategory items there are.
I have a legacy class database that is represented by the following model.
public class Course
{
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public CourseLevel Level { get; set; }
public float FullPrice { get; set; }
public Author Author { get; set; }
public IList<Tag> Tags { get; set; }
public IList<Attendee> Attendees { get; set; }
}
public class Attendee
{
public int Id { get; set; }
public int StudentId { get; set; }
public decimal Tuition { get; set; }
public Student Student { get; set; }
}
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
public class Author
{
public int Id { get; set; }
public string Name { get; set; }
public IList<Course> Courses { get; set; }
}
public class Tag
{
public int Id { get; set; }
public string Name { get; set; }
public IList<Course> Courses { get; set; }
}
I need to get a list of classes that either a part of the course title or description or a part of a student's name matches my search string. The first part is easy.
List<Course> courses = db.Courses.Where(w => w.Title.IndexOf(searchString) > -1 || w.Description.IndexOf(searchString) > -1).ToList();
How do I now filter against w.Attendees.Student.Name?
I tried:
List<Course> courses = db.Courses
.Where(w => w.Title.IndexOf(searchString) > -1 ||
w.Description.IndexOf(searchString) > -1 ||
w.Attendees.Any(a => a.Student.Name.IndexOf(searchString) > -1)).ToList();
And it just returns an empty list.
I'm still kind of new to Linq, I'm coming from Grails. Any help is appreciated.
Try running only w.Attendees.Any(a => a.Student.Name.IndexOf(searchString) and debugging it because Attendees could be null or empty, and the same is true for the Student property.
Also, in the off chance that your database isn't case insensitive, you should consider changing your code to reflect that:
w.Attendees.Any(a => a.Student.Name.ToLowerInvariant().Contains(searchString.ToLowerInvariant())
The case sensitiveness could be the source of your problems too.
Try this:
List<Course> courses = db.Courses
.Where(w => w.Title.Contains(searchString)||
w.Description.Contains(searchString) ||
w.Attendees.Any(a => a.Student.Name.Contains(searchString))).ToList();
I have my models like this:
Goup.cs
GroupUser (pivot table)
ApplicationUser (User) -> 4. Profile
And now I want to show the data in Profile on a details page when the User belongs to the group. I'm doing this like this:
private IEnumerable<GroupUser> GetUsers(int groupId)
{
IEnumerable<GroupUser> model = null;
if(groupId == 0)
{
model = _kletsContext.GroupUser.OrderByDescending(o => o.GroupId).AsEnumerable();
}
else
{
model = _kletsContext.GroupUser.Where(g => g.GroupId == groupId).Include(p => p.User.Profile).OrderByDescending(o => o.GroupId).AsEnumerable();
}
return model;
}
This works, if I just want to display the UserId, ... (so the data in the Pivot table) with this code:
#model IEnumerable<App.Models.GroupUser>
#if(Model != null && Model.Count() > 0)
{
#foreach(var user in Model)
{
#user.UserId</h2>
}
}
But for some reason I can't display the data in the Included tables?
Normally you would do something like this: #user.User.Profile.XXXX but then I get the error: System.NullReferenceException: Object reference not set to an instance of an object
So this would mean the return is null, but there are users in the pivot table with a profile.
The models:
Group.cs:
namespace App.Models
{
public class Group : Item
{
public Group() : base()
{
}
[Key]
public Int16 Id { get; set; }
public string Name { get; set; }
public string Images { get; set; }
/* Foreign Keys */
public Nullable<Int16> RegionId { get; set; }
public virtual Region Region { get; set; }
public virtual ICollection<Lets> Lets { get; set; }
public virtual ICollection<GroupUser> Users { get; set; }
}
}
ApplicationUser:
namespace App.Models.Identity
{
public class ApplicationUser : IdentityUser
{
public string Description { get; set; }
public DateTime CreatedAt { get; set; }
public Nullable<DateTime> UpdatedAt { get; set; }
public Nullable<DateTime> DeletedAt { get; set; }
/* Virtual or Navigation Properties */
public virtual Profile Profile { get; set; }
public virtual ICollection<GroupUser> Groups { get; set; }
public virtual ICollection<Lets> Lets { get; set; }
public virtual ICollection<Category> Categories { get; set; }
public virtual ICollection<Region> Regions { get; set; }
public virtual ICollection<Status> Status { get; set; }
public virtual ICollection<Tag> Tags { get; set; }
}
}
GroupUser:
namespace App.Models
{
public class GroupUser
{
public GroupUser()
{
}
public Nullable<Int16> GroupId { get; set; }
public string UserId { get; set; }
public virtual Group Group { get; set; }
public virtual ApplicationUser User { get; set; }
}
}
Profile.cs:
namespace App.Models
{
public class Profile : Item
{
public Profile() : base()
{
}
[Key]
public string UserId { get; set; }
public string FirstName { get; set; }
public string SurName { get; set; }
public string Email { get; set; }
public string Gender { get; set; }
public Int16 Age { get; set; }
public string City { get; set; }
public string Image { get; set; }
public Int16 Credits { get; set; }
public Int16 Postalcode { get; set; }
}
}
How can i display the nested data with razor?
model = _kletsContext.GroupUser.Where(g => g.GroupId == groupId)
.Include(gu => gu.User)
.ThenInclude(u => u.Profile)
.OrderByDescending(o => o.GroupId)
.AsEnumerable();
Don't get freaked out when intellisense doesn't work for the ThenInclude, just type it, it will compile.
try to include the user-reference
model = _kletsContext.GroupUser.Where(g => g.GroupId == groupId).Include(p => p.User).Include(p => p.User.Profile).OrderByDescending(o => o.GroupId).AsEnumerable();