How to make DTOs for complex models - .net-core

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

Related

I'm getting this error while updating the db

public class Product
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ProductId{ get; set; }
public string Name{ get; set; }
public string Description { get; set; }
public double Price { get; set; }
public int Stock{ get; set; }
public bool IsApproved { get; set; }
public bool IsHome { get; set; }
public DateTime CreatedDate{ get; set; }
public List<ProductImage> ProductImages { get; set; }
[DisplayName("Subcategory")]
public int SubCategoryId { get; set; }
[ForeignKey("SubCategoryId")]
public virtual SubCategory SubCategory { get; set; }
}
public class Category
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
[DisplayName("Category")]
public string Name { get; set; }
public virtual IList<SubCategory> SubCategories { get; set; }
}
public class SubCategory
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
public string Name { get; set; }
[DisplayName("Category")]
public int CategoryId { get; set; }
[ForeignKey("CategoryId")]
public virtual Category Category { get; set; }
public virtual IList<Product> Products { get; set; }
}
And here are the DBSets in the DbContext:
public DbSet<Product> Products { get; set; }
public DbSet<ProductFavorite> ProductFavorites{ get; set; }
public DbSet<ProductImage> ProductImages { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<SubCategory> SubCategories { get; set; }
public DbSet<Member> Members { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<Blog> Blogs { get; set; }
I give migrations the update-database command, I get the following error:
Error Number:1767,State:0,Class:16
"Foreign key 'FK_Products_Categories_CategoryId' references invalid table 'Categories'.
Could not create constraint. See previous errors."
Thanks in advance for your interest.

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.

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?

Database model for users with multiple capabilities

In another question, I explain my goal to create 2 different types of users with different capabilities in my ASP.Net MVC 5 website. I wonder how I would be able to modify my current database models to hold the related information based on their type. My current models are as follows:
public class User : IUser
{
public User()
: this(String.Empty)
{
}
public User(string userName)
{
UserName = userName;
Id = Guid.NewGuid().ToString();
}
[Key]
public string Id { get; set; }
[Required]
public string UserName { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
public string Phone { get; set; }
public string MobilePhone { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
public virtual IList<UserAddress> Addresses { get; set; }
}
public class Restaurant
{
[Key]
public int ID { get; set; }
[Required]
public string Name { get; set; }
public virtual IList<RestaurantAddress> Addresses { get; set; }
public virtual IList<RestaurantFood> Menu { get; set; }
public virtual IList<Review> Reviews { get; set; }
[DataType(DataType.Url)]
public string Website { get; set; }
[DataType(DataType.PhoneNumber)]
public string Phone { get; set; }
[DataType(DataType.PhoneNumber)]
public string Fax { get; set; }
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
public int Seats { get; set; }
public double AverageRating { get; set; }
public double AveragePrice { get; set; }
}
One solution that comes to my mind is to move the additional info of the User class to another class and hold the foreign key for the related model in the basic user info class. Something like:
public class User : IUser
{
public User()
: this(String.Empty)
{
}
public User(string userName)
{
UserName = userName;
Id = Guid.NewGuid().ToString();
}
[Key]
public string Id { get; set; }
[Required]
public string UserName { get; set; }
public virtual ExtendedUser NormalUserInfo { get; set; }
public virtual Restaurant RestaurantInfo { get; set; }
}
public class ExtendedUser
{
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
public string Phone { get; set; }
public string MobilePhone { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
public virtual IList<UserAddress> Addresses { get; set; }
}
public class Restaurant
{
[Key]
public int ID { get; set; }
[Required]
public string Name { get; set; }
public virtual IList<RestaurantAddress> Addresses { get; set; }
public virtual IList<RestaurantFood> Menu { get; set; }
public virtual IList<Review> Reviews { get; set; }
[DataType(DataType.Url)]
public string Website { get; set; }
[DataType(DataType.PhoneNumber)]
public string Phone { get; set; }
[DataType(DataType.PhoneNumber)]
public string Fax { get; set; }
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
public int Seats { get; set; }
public double AverageRating { get; set; }
public double AveragePrice { get; set; }
}
and in controller:
User user = BuildUser();
ExtendedUser normal = BuildNormalUser();
Restaurant rest = BuildRestaurant();
if (model.Type == UserType.NormalUser)
user.NormalUserInfo = normal;
else
user.RestaurantInfo = normal;
However, I'm not sure that this is the right thing to do.

Resources