Need to create an API on the basis of ForeignKey in dotnet core - .net-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.

Related

How to make DTOs for complex models

My target with the below mentioned classes is to make one DTOs class out of these classes and register AppUser in sqlite database. I use Identity core. I thank you for every body who has given me help on solving this problem.
By the way: is that possible to have virutal properties inside DTO classes? Other thing which i am struggling with is on how to handle the incoming user input (in this case DTO). I get the following error time and again Cannot implicitly convert type int to Backend.Data.Gender. I Cannot implicitly convert type Backend.Data.Work_Experience to System.Collections.Generic.List<Backend.Data.Work_Experience>
public class AppUser : IdentityUser<int>
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Description { get; set; }
virtual public Gender Gender { get; set; }
virtual public ICollection<Interest> Interests {get; set;}
virtual public List<Education> Education { get; set; }
virtual public List<Work_Experience> Work_Experiences { get; set; }
virtual public List<Answer> Answers { get; set; }
}
public class Interest
{
[Key]
public int Id { get; set; }
public string InterestName{ get; set; }
public virtual ICollection<AppUser> Users { get; set; }
}
public class Education
{
[Key]
public int EducationsId { get; set; }
public string SchoolName { get; set; }
public string Field_Of_Study { get; set; }
public string StudyPath { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public int DegreeId { get; set; }
public virtual Degree Degree { get; set; }
public int UserId { get; set; }
public virtual AppUser User { get; set; }
}
public class Degree
{
[Key]
public int DegreesId { get; set; }
public string DegreeName { get; set; }
}
public class Gender
{
[Key]
public int GenderId { get; set; }
public string GenderName { get; set; }
}
public class Work_Experience
{
[Key]
public int WorkExperiencesId { get; set; }
public string JobTitle { get; set; }
public string CompanyName { get; set; }
public string Industry { get; set; }
public string Field_Of_Work { get; set; }
public int UserId { get; set; }
public virtual AppUser User { get; set; }
}
public class Question
{
[Key]
public int QuestionsId { get; set; }
public string Question_text { get; set; }
}
public class Answer
{
[Key]
public int AnswersId { get; set; }
public string Answer_text { get; set; }
public int QuestionId { get; set; }
public virtual Question Question { get; set; }
public int UserId { get; set; }
public virtual AppUser User { get; set; }
}

How to get data in many to many relationship and return AsQueryable in Entity Framework

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; }
}

Entity Framework many to many relation error

I'm trying to create a many-to-many relationship between my two tables, but when I run Update-Database command I get this error:
Introducing FOREIGN KEY constraint 'FK_dbo.ExamQuestions_dbo.Questions_Question_Id' on table 'ExamQuestions' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint or index. See previous errors.
My first entity is :
public class Question
{
public Question()
{
this.Exams = new HashSet<Exam>();
}
[Key]
public int Id { get; set; }
[Required(ErrorMessage="Question is Required")]
[Display(Name="Question")]
[AllowHtml]
public string QuestionText { get; set; }
// public bool IsMultiSelect { get; set; }
public string Hint { get; set; }
public string HelpLink { get; set; }
public int Marks { get; set; }
public byte[] ImageData { get; set; }
[StringLength(50)]
public string MimeType { get; set; }
public byte[] Audio { get; set; }
public int QuestionTypeId { get; set; }
public int TopicId { get; set; }
public int DifficulityLevelId { get; set; }
public int SubjectId { get; set; }
public DifficultyLevel QuestionDifficulity { get; set; }
public Topic Topic { get; set; }
public virtual ICollection<Option> Options { get; set; }
public ICollection<Exam> Exams { get; set; }
}
And the second entity is:
public class Exam
{
public Exam()
{
this.Questions = new HashSet<Question>();
}
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public int Duration { get; set; }
[Required]
public int TotalQuestion { get; set; }
[Required]
public int TotalMarks { get; set; }
public bool SectionWiseTime { get; set; }
public bool QuestionWiseTime { get; set; }
public bool AllQustionRequired { get; set; }
public bool AllowBackForward { get; set; }
public bool SuffleSubjectWise { get; set; }
public bool SuffleOptionWise { get; set; }
public bool GroupSubjectWise { get; set; }
[Required]
public int ExamTypeId { get; set; }
[Required]
public int ExamInstructionId { get; set; }
[Required]
public int DifficultyLevelId { get; set; }
public virtual ExamType ExamType { get; set; }
public virtual ExamInstruction ExamInstruction { get; set; }
public virtual DifficultyLevel DifficultyLevel { get; set; }
public virtual ICollection<Question> Questions { get; set; }
//public virtual ICollection<ExamSchedule> ExamSchedules { get; set; }
}
Can someone tell me where I'm going wrong?
By default, EF has cascading deletes set. This error is warning you that this can cause cascading deletes with many to many relationships. And is probably not what you intend to have happen on a delete/update.
You can remove the OneToManyCascadeDeleteConvention in the OnModelCreating method, or on the fluent mapping for each entity.
Details are provided in this SO Answer

Mapping existing database with code first approch

I have implemented asp .net application without Code first approach. now i want to build different system with existing database and code first.
public class EmployeeEntity
{
public int Id { get; set; }
public string ResourceCode { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
public int Gender { get; set; }
public int Status { get; set; }
public string NIC { get; set; }
}
now i want to add code first entities.
[Table("ExternalApplicantEntity")]
public class ExternalApplicantEntity
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ApplicantID { get; set; }
//[ForeignKey("EmployeeEntity")]
//public int Created_By { get; set; }
//public virtual EmployeeEntity EmployeeEntity { get; set; }
public string NIC { get; set; }
public string Mobile { get; set; }
public string Institute { get; set; }
how i combine these codes?

MVVMCross Community SqLite - Relationship between tables

I have two simple tables as follow:
public class MediaPartner
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string PhoneNumber { get; set; }
public string CompanyName { get; set; }
public double Lat { get; set; }
public double Lng { get; set; }
public DateTime InsertedUtc { get; set; }
}
public class ImageGroup
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public List<MediaPartner> IdMediaPartner { get; set; }
public string ImagePath { get; set; }
public bool IsSent { get; set; }
public DateTime InsertedUtc { get; set; }
}
The problem:
public List< MediaPartner > IdMediaPartner { get; set; }
OR
public MediaPartner IdMediaPartner { get; set; }
does not compile.
My question is: Is there a way to build one-to-many relationship between these two tables?
Thank you!
SQLite-net only provides cross-table referencing using indexing like:
public class Stock
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
[MaxLength(8)]
public string Symbol { get; set; }
}
public class Valuation
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
[Indexed]
public int StockId { get; set; }
public DateTime Time { get; set; }
public decimal Price { get; set; }
}
There is at least one extension to sqlite-net which allows OneToMany attributes to be declared - see https://bitbucket.org/twincoders/sqlite-net-extensions which enables code like:
public class Stock
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
[MaxLength(8)]
public string Symbol { get; set; }
[OneToMany] // One to many relationship with Valuation
public List<Valuation> Valuations { get; set; }
}
public class Valuation
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
[ForeignKey(typeof(Stock))] // Specify the foreign key
public int StockId { get; set; }
public DateTime Time { get; set; }
public decimal Price { get; set; }
[ManyToOne] // Many to one relationship with Stock
public Stock Stock { get; set; }
}
I'm not sure of the exact implementation of this - e.g. I don't know if this uses real FOREIGN KEY constraints - but the code is open source, is under active development, has mvvmcross plugin support built-in, is cross platform and is available for forking and for contributions.

Resources