How to get data in many to many relationship and return AsQueryable in Entity Framework - asp.net

How I can get book AsQueryable with category name in bookParams?
It can be implemented in any way as long as it returns AsQueryable to I can do pagination.
Thanks for any help.
BookService.cs
public async Task<PagedList<Book>> GetBooksAsync(BookParams bookParams)
{
var query = repository.context.Books.AsQueryable();
// query to get books with category name
return await PagedList<Book>.CreateAsync(query, bookParams.pageNumber, bookParams.pageSize);
}
Book.cs
public class Book: IEntity
{
public int Id { get; set; }
public string Title { get; set; }
public virtual ICollection<BookCategory> BookCategories { get; set; }
}
Category.cs
public class Category: IEntity
{
public int Id { get; set; }
public string Name { get; set; }
public virtual List<BookCategory> BookCategories { get; set; }
}
BookCategory.cs
public class BookCategory: IEntity
{
public int Id { get; set; }
public int BookId { get; set; }
public virtual Book Book { get; set; }
public int CategoryId { get; set; }
public virtual Category Category { get; set; }
}

Related

how to get related model data in View model - One to Many Relation

I know this is asked question but I confused what's the best practice to get data from a related model in View Model.
I want to show the review or comment data in view with category Name but in View Model CategoryId is just exist.
My question is should I add list of categories in Vm and find intended category by categoryId in View or there is better and optimized solution for this situation.
Review Model :
public class Review
{
public int Id { get; set; }
public string Author { get; set; }
[MaxLength(500)]
public string Body { get; set; }
public int Rating { get; set; }
public bool IsBuyer { get; set; }
public int CategoryId { get; set; }
public Category Category { get; set; }
}
Comment Model :
public class Comment
{
public int Id { get; set; }
public string Author { get; set; }
[MaxLength(500)]
public string Body { get; set; }
public int CategoryId { get; set; }
public Category Category { get; set; }
}
Category Model :
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public string Type { get; set; }
public string Description { get; set; }
public List<Comment> Comment { get; set; }
public List<Review> Review { get; set; }
}
Vm :
public class RevComVm
{
public Review Review { get; set; }
public Comment Comment { get; set; }
public List<Review> Reviews { get; set; }
public List<Comment> Comments { get; set; }
}
Finally, I added List of categories to View Model to access review/comment category and find specific record by CategoryId that saved in model using linq.
public class RevComVm
{
public Review Review { get; set; }
public Comment Comment { get; set; }
public List<Review> Reviews { get; set; }
public List<Comment> Comments { get; set; }
public List<Category> Categories {get; set;}
}

Expression of type 'System.Collections.Generic.List`1[API.Entities.CompanySetting]' cannot be used for parameter of type 'System.Linq.IQueryable

I am trying to find a simple way using AutoMapper to return all companies that are linked to a specific User Id in a many-to-many relationship scenario. I followed the SO Automapper many to many mapping but I get the error message "Expression of type 'System.Collections.Generic.List`1[API.Entities.CompanySetting]' cannot be used for parameter of type 'System.Linq.IQueryable" when trying to follow the logic.
My AppUser entity:
public class AppUser
{
public int Id { get; set; }
public string UserName { get; set; }
public virtual ICollection<AppUserCompanySetting> AppUserCompanySettings { get; set; } = new List<AppUserCompanySetting>();
}
My CompanySetting entity:
public class CompanySetting
{
public int Id { get; set; }
public string CompanyName { get; set; }
public string CompanyRegistrationNumber { get; set; }
public bool isActive { get; set; }
public bool isArchived { get; set; }
public virtual ICollection<AppUserCompanySetting> AppUserCompanySettings { get; set; } = new List<AppUserCompanySetting>();
}
And I have the Join table
public class AppUserCompanySetting
{
public int AppUserId { get; set; }
public virtual AppUser AppUser { get; set; }
public int CompanySettingsId { get; set; }
public virtual CompanySetting CompanySettings { get; set; }
}
I then created a CompanySettingDto
public class CompanySettingDto
{
public int Id { get; set; }
public string CompanyName { get; set; }
public string CompanyRegistrationNumber { get; set; }
public bool isActive { get; set; }
public bool isArchived { get; set; }
}
And a MemberDto:
public class MemberDto
{
public int Id { get; set; }
public string Username { get; set; }
public string PhotoUrl { get; set; }
public string KnownAs { get; set; }
public int TimeActive { get; set; }
public DateTime LastActive {get; set;}
public ICollection<PhotoDto> Photos { get; set; }
public ICollection<CompanySettingDto> CompanyInformation { get; set; }
}
I then tried Automapper to bring the relationships between the User and the Company Information I require:
public class AutoMapperProfiles : Profile
{
public AutoMapperProfiles()
{
CreateMap<AppUser, MemberDto>()
.ForMember(dest => dest.CompanyInformation, opt => opt.MapFrom(x => x.AppUserCompanySettings.Select(y => y.CompanySettings).ToList()))
CreateMap<CompanySetting, CompanySettingDto>();
}
}
I am writing an API call to get all companies that are linked to a specific UserId.
public async Task<IEnumerable<MemberDto>> GetCompaniesByUserIdAsync(int userId)
{
return await _context.Users
.Where(x => x.Id == userId)
.ProjectTo<MemberDto>(_mapper.ConfigurationProvider)
.ToListAsync();
}

Need to create an API on the basis of ForeignKey in dotnet core

Here is my Schema and with two Foreign Key in an intermediate table. I am beginner in Core dotnet so unable to crate API to show the department in the school.
public class DepartmentSchool
{
public int Id { get; set; }
public int DepartmentID { get; set; }
[ForeignKey("DepartmentID")]
public virtual Department Department{ get; set; }
public int SchoolsId { get; set; }
[ForeignKey("SchoolsId")]
public virtual Schools Schools { get; set; }
Here I want to get all department related to school id, how can i get all the department though the School id in dotnetcore API.
Here is the school class entity schema.
public partial class Schools
{
public int ID { get; set; }
public string UicCode { get; set; }
public int SchoolSystemsId { get; set; }
public string BannerUrl { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string ImageUrl { get; set; }
public int UserID { get; set; }
public int? Status { get; set; }
public DateTime? CreatedAt { get; set; }
public int? CreatedBy { get; set; }
public DateTime UpdatedAt { get; set; }
public int? ModifiedBy { get; set; }
[ForeignKey("SchoolSystemsId")]
public PrivateSchoolSystem PrivateSchoolSystems { get; set; }
And more here is the department schema.
public partial class Department
{
public int Id { get; set; }
public string Title { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
public int CreatedBy { get; set; }
public int UpdatedBy { get; set; }
public int SchoolSystemsID { get; set; }
[ForeignKey("SchoolSystemsID")]
public virtual PrivateSchoolSystem PrivateSchoolSystems { get; set; }
And I am trying to get a department list in the query in the following controller.
[Route("api/[controller]")]
[ApiController]
public class DepartmentSchoolController : ControllerBase
{
private readonly learning_gpsContext _learning_GpsContext;
public DepartmentSchoolController(learning_gpsContext learning_GpsContext)
{
_learning_GpsContext = learning_GpsContext;
}
[HttpGet("school/{schoolId}/departments")]
public IActionResult GetDepartmentsFromSchool(int schoolId)
{
var school = _learning_GpsContext.Schools.Where(e=>e.Id == schoolId).FirstOrDefault();
if (school == null)
return NotFound();
var departments = _learning_GpsContext.DepartmentSchool
.Where(e=>e.SchoolsId == schoolId).Select(e=>e.Department);
return Ok(departments);
}
For further learning check this tutorial. You should also understand what REST is and for basic questions always take a look at the official documenation.

Non lazy loading

i have a model looks like this.
public class TradeModel
{
public int id { get; set; }
public BaseProductModel baseProduct { get; set; }
public string productDescription { get; set; }
public List<byte[]> images { get; set; }
public int price { get; set; }
// Date infos
public DateTime estimatedShippingDate { get; set; }
}
What i want to do is. when i call post request i want to send an id of an existing baseProduct not the entire baseProductForm and that being created.
ive tried
[Required]
public int baseProductId { get; set; }
[ForeignKey("baseProductId")]
public virtual BaseProductModel baseProduct { get; set; }
something like this, but seems to be not working.
any possible solutions?
Your model:
public class TradeModel
{
public int id { get; set; }
public int baseProductId { get; set; }
public virtual BaseProductModel baseProduct { get; set; }
public string productDescription { get; set; }
public List<byte[]> images { get; set; }
public int price { get; set; }
// Date infos
public DateTime estimatedShippingDate { get; set; }
}
Your ViewModel:
public class TradeViewModel
{
public int id { get; set; }
public int baseProductId { get; set; }
public string productDescription { get; set; }
public List<byte[]> images { get; set; }
public int price { get; set; }
// Date infos
public DateTime estimatedShippingDate { get; set; }
}
Now you can pass only the baseProductId:
public IActionResult(TradeViewModel model)
{
// Your form will contain only the id anyway so the method below should work.
// Replace that with your actual context
//dbcontext.Trades.Add(new TradeModel { ... });
}

Model collections of the same class held by several other classes

How do I model the following using Castle ActiveRecord?
I have two classes, Customer and Task.
I would like to reuse a third class, Note, stored in a Collection in each of the Customer and Task classes.
public class Note
{
public int ID { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
}
public class Customer
{
public int ID { get; set; }
public IList<Note> Notes { get; set; }
}
public class Task
{
public int ID { get; set; }
public IList<Note> Notes { get; set; }
}
I would then like to be able to pass the Notes collection to a Gridview, Listview or Repeater in the relevant ASP.Net page for the Customer or Task classes.
I think what you need is to implement a type hierarchy. You can read about it here.
We settled on the following pattern:
[ActiveRecord]
public class Note
{
[PrimaryKey]
public int ID { get; set; }
[Property]
public string Subject { get; set; }
[Property]
public string Body { get; set; }
[BelongsTo]
public Customer Customer { get; set; }
[BelongsTo]
public Customer Task{ get; set; }
}
[ActiveRecord]
public class Customer
{
[PrimaryKey]
public int ID { get; set; }
[HasMany]
public IList<Note> Notes { get; set; }
}
[ActiveRecord]
public class Task
{
[PrimaryKey]
public int ID { get; set; }
[HasMany]
public IList<Note> Notes { get; set; }
}

Resources