How to create a history model of a specific model on MVC 4 - asp.net-mvc-4

I'm still new in creating Models using Entity Framework and MVC 4 Razor. I'm having a problem on how can I save a history of a model. How can I create a model that have a history on specific tables or fields ? For ex: If I wish to create a history on the changes on the school. Its still not clear to me how will I I create the model that saves history. How will be the triggering do I have to execute the save function on different models with the same data ?
Thank you so much in advance.
If anyone could be a simple example of model and a model history and how it is functioning, I'll be very grateful. Like a Sales or sales history.
Here's my code
One To Many
public class Child
{
[Key]
public int ChildID { get; set; }
[Required,Display(Name="Project Code")]
public string ProjectCode { get; set; }
public string Status { get; set; }
[DataType(DataType.Date)]
public DateTime StatusDate { get; set; }
public string FamilyName { get; set; }
public string GivenName { get; set; }
public string MiddleName { get; set; }
[DataType(DataType.Date)]
public DateTime Birthdate { get; set; }
public string Gender {get;set;}
public string Address { get; set; }
public string Section { get; set; }
public int SchoolLevelID { get; set; }
public int SchoolYearID { get; set; }
public int AreaID { get; set; }
public int SchoolID { get; set; }
public int GradeLevelID { get; set; }
//Foreign Key - One to Many
public virtual SchoolLevel SchoolLevel { get; set; }
public virtual SchoolYear SchoolYear { get; set; }
public virtual Area Area { get; set; }
public virtual School School { get; set; }
public virtual GradeLevel GradeLevel{get;set;}
//Child is foreign key at the table
public virtual ICollection<Guardian> Guardians { get; set; }
}
public class SchoolLevel
{
public int SchoolLevelID { get; set; }
public string SchoolLevelName { get; set; }
public virtual ICollection<Child> Children { get; set; }
}
public class SchoolYear
{
public int SchoolYearID { get; set; }
public string SchoolYearName { get; set; }
public virtual ICollection<Child> Children{get;set;}
}
public class Area
{
public int AreaID{get;set;}
public string AreaName { get; set; }
public virtual ICollection<Child> Children{get;set;}
}
public class School
{
public int SchoolID { get; set; }
public string SchoolName{get;set;}
public virtual ICollection<Child> Children { get; set; }
}
public class GradeLevel
{
public int GradeLevelID{get;set;}
public string GradeLevelName { get; set; }
public virtual ICollection<Child> Children { get; set; }
}
public class ChildDbContext : DbContext
{
public DbSet<Child> Children { get; set; }
public DbSet<SchoolLevel> SchoolLevels { get; set; }
public DbSet<SchoolYear> SchoolYears { get; set; }
public DbSet<Area> Areas { get; set; }
public DbSet<School> Schools { get; set; }
public DbSet<GradeLevel> GradeLevels { get; set; }
public DbSet<Guardian> Guardians { get; set; }
}

You can use this approach: Create a History model. That contains 1 changeness like o log.
public class History
{
public int HistoryId { get; set; }
public int ModelType { get; set; } //it is ModelTypeEnum value.
public int ModelId { get; set; }
public string PropertyName { get; set; }
public string Propertyvalue {get;set;}
public DateTime ChangeDate { get; set; }
public int ChangedUserId { get; set; }
}
And Enum:
public enum ModelTypeEnum
{
Child =1,
SchoolLevel = 2,
//etc..
};
For example, when you edit 1 Child entity, give changed properties name and value, it's id, type and others (ChangeDate, ChangedUserId) to History and save histories. If 3 properties will change you should save 3 history entities. Then, you can load (filter) histories by ModelId, by ChangedUserId etc.

Related

How to ignore nested models in Swagger (ASP.Net Core 3.1)?

I have a complex model with multiple levels, i am using Swashbuckle.
how can I ignore related models in swagger UI? and show just the first level of the model?
See the below example, I want to ignore all relations like JobTitleVM and ICollection.
public class UserVM
{
public int Id { get; set; }
public Guid Guid { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Token { get; set; }
public string Avatar { get; set; }
public int IsActive { get; set; }
public int JobTitleId { get; set; }
public JobTitleVM JobTitle { get; set; }
public int UserStatusId { get; set; }
public UserStatusVM UserStatus { get; set; }
public virtual ICollection<UserStepsVM> UserSteps { get; set; } = new List<UserStepsVM>();
}

Missing type map configuration or unsupported mapping.for Collection of DTO

I was making an API for saving a model where it has one to many relationship with another model. When I applying automapping in it. it is giving me following error:
CreateContestDto -> Contest
tritronAPI.DTOs.CreateContestDto -> tritronAPI.Model.Contest
Type Map configuration:
CreateContestDto -> Contest
tritronAPI.DTOs.CreateContestDto -> tritronAPI.Model.Contest
Destination Member:
Problems
---> AutoMapper.AutoMapperMappingException: Missing type map
configuration or unsupported mapping.
Mapping types:
ProblemDto -> Problem
tritronAPI.DTOs.ProblemDto -> tritronAPI.Model.Problem
at lambda_method(Closure , ProblemDto , Problem , ResolutionContext )
My models are: Contest and Problem a contest contain many problems:
public class Contest
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public ICollection<Problem> Problems { get; set; }
public ICollection<ContestProgrammingLanguage>
ContestProgrammingLanguages { get; set; }
}
public class Problem
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
[MaxLength(255)]
public string ProblemName { get; set; }
[ForeignKey("User")]
public string ProblemAuthorId { get; set; }
public virtual User ProblemAuthor { get; set; }
public string AuthorName { get; set; }
//public virtual List<Resources> Resourceses { get; set; }
public string ProblemDescription { get; set; }
public bool IsPublished { get; set; }
public virtual ICollection<Submission> Submissions { get; set; }
public string Tags { get; set; }
//public Guid Contest_Id { get; set; }
public virtual Contest Contest { get; set; }
[ForeignKey("Contest")]
public int? Contest_Id { get; set; }
public short Score { get; set; }
//Timelimit in miliseconds
public int TimeLimit { get; set; }
//MemoryLimit in bytes
public int MemoryLimit { get; set; }
//More than source code limit is not allowed
public int? SourceCodeLimit { get; set; }
public virtual ICollection<TestFile> TestFiles { get; set; } = new
List<TestFile>();
}
public class CreateContestDto
{
public CreateContestDto()
{
this.Problems = new HashSet<ProblemDto>();
}
public string Name { get; set; }
public DateTime StartDate { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndDate { get; set; }
public DateTime EndTime { get; set; }
public string BackgroundImage { get; set; }
public string Description { get; set; }
public ICollection<ProblemDto> Problems { get; set; }
}
public class ProblemDto
{
public int Id { get; set; }
public string ProblemName { get; set; }
}
mapping profile:
CreateMap<CreateContestDto, Contest>().ForMember(
dest => dest.Problems , opt => opt.MapFrom(src =>
src.Problems));
controller code:
public async Task<IActionResult> AddContest([FromBody]
CreateContestDto contest)
{
var con = _mapper.Map<Contest>(contest);
this._uow.ContestRepository.Add(con);
return Ok();
}
I have already tried with reversemap selecting new id in mapping profile
You also need to add mappings for ProblemDTO to Problem:
CreateMap<CreateContestDto, Contest>();
CreateMap<ProblemDto, Problem>();

Unable to determine the principal end of an association , One to One relation of SQL

This is my error :
Unable to determine the principal end of an association between the types 'SANTEK.Web.Models.SantekOrder' and 'SANTEK.Web.Models.OrderMoneySum'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.
What is my mistake logically ?? I mean to build one-to-one relation.
My model classes are here :
[Table("Orders")]
public class SantekOrder
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int SantekOrderId { get; set; }
[Required, StringLength(25)]
[DisplayName("Çatdırılacaq şəxs")]
public string DelivaryManName { get; set; }
[DisplayName("Çatdırılacaq şəxs istifadəçidir?")]
public bool DeliveryManIsUser { get; set; }
[Required, StringLength(25)]
[DisplayName("Çatdırılacaq şəxs ad və soyadı")]
public string DelivaryManSurname { get; set; }
[Required, StringLength(10)]
[DisplayName("Çatdırılacaq şəxs tefon nömrəsi")]
public string DelivaryManTel { get; set; }
[DisplayName("Çatdırılacaq ünvan istifadəçinin ünvandır?")]
public bool IsUserAddress { get; set; }
[Required, StringLength(150)]
[DisplayName("Çatdırılacaq şəxsin ünvanı?")]
public string DelivaryManAddress { get; set; }
public int SanTekUserId { get; set; }
public int OrderMoneySumId { get; set; }
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy-hh-mm-ss}",
ApplyFormatInEditMode = true)]
public DateTime Time { get; set; }
[ForeignKey("SanTekUserId")]
public virtual SanTekUser SanUser { get; set; }
[ForeignKey("SanTekUserId")]
public virtual OrderMoneySum OrderMoneySum { get; set; }
}
This is my OrdersDetail Table to hold all product and their quantity
[Table("OrderedProducts")]
public class OrderMoneySum
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int OrderMoneySumId { get; set; }
[Required]
public int SantekOrderId { get; set; }
[Required]
public int AllProductId { get; set; }
[DisplayName("Miqdarı")]
public int Quantity { get; set; }
[ForeignKey("SantekOrderId")]
public virtual SantekOrder SantekOrder { get; set; }
[ForeignKey("SantekOrderId")]
public virtual AllProduct AllProduct { get; set; }
}

not able to get subcategory of particular category in mvc 4 and designing issue of category and subcategory model class

i am working on help desk system in mvc.
i have only one master table for user and technicians.
this is my category class:
public class Category
{
[Key]
public int CategoryId { get; set; }
public string Name { get; set; }
public virtual ICollection<SubCategory> subCategory { get; set; }//category can have more than 1 category
}
This is my Subcategory:
public class SubCategory
{
[Key]
public int SubcategoryId { get; set; }
public string Name { get; set; }
public int CategoryId { get; set; }
public virtual ICollection<TicketInfo> ticketsInfo { get; set; }/to keep track of all tickets under this particular subcategory.
public virtual ICollection<UserDetails> technicianInfo { get; set; }//to keep track of technician and user under this subcategory.
public virtual Category category { get; set; }
}
This is my usermaster(it defines both user and technician)
public class UserDetails
{
public string UserName { get; set; }
[Key]
public int UserId { get; set; }
public string FName { get; set; }
public string LName { get; set; }
public string PhoneNo { get; set; }
public string EmailId { get; set; }
[DataType(DataType.Password)]
public string Password { get; set; }
public int SubcategoryId { get; set; }
public int AddressId { get; set; }
public Boolean IsActive { get; set; }
public DateTime CreatedDate { get; set; }
public virtual ICollection<Role> Roles { get; set; }
public virtual SubCategory subCategory { get; set; }
}
now when i am firing dis query::
public list<Category> FetchTicketDetailsforSubcategory(int categoryId)
{
using (HelpDeskdbContext context = new HelpDeskdbContext())
{
var category = from temp in context.Category where temp.CategoryId == categoryId select temp;
return category;
}
}
it just show me the category but not subcategory under that category.
it show me this on subcategory:The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
can any one figure out what is wrong with my class design??
try this
context.Category.Where(x=>x.CategoryId == categoryId).SelectMany(x=>x.subCategory).ToList()

Adding checkboxes in MVC4

I have searched and was unable to find a way to display checkboxes in my view. I have 2 entities: Assignment and Chore which is a one-to-many relationship (one assignment, many chores)
public class Chore
{
public System.Guid ChoreId { get; set; }
public string ChoreName { get; set; }
public string Description { get; set; }
public int PointValue { get; set; }
}
public class Assignment
{
public int AssignmentId { get; set; }
public System.Guid RecipientId { get; set; }
public Nullable<bool> Completed { get; set; }
public System.DateTime AssignedDate { get; set; }
public Nullable<System.DateTime> CompletedDate { get; set; }
public virtual IEnumerable<Chore> Chores { get; set; }
}
How can I display a list of all possible chores That I can select whenever I want to create an assignment?