EF 6 Code First not create database - asp.net-mvc-4

I searched many solutions but I can't understand why database does not create? My classes and context class are very simple.
public class News
{
[Key]
public int NewsID { get; set; }
public string NewsHeader { get; set; }
public string News { get; set; }
public int CategoryID;
public virtual Category Category { get; set; }
}
public class Category
{
[Key]
public int CategoryID { get; set; }
public string CategoryName{ get; set; }
public virtual ICollection<News> Newss { get; set; }
}
public class NewsContext: DbContext
{
public NewsContext(): base("NewsContext")
{
Database.SetInitializer<NewsContext>(new CreateDatabaseIfNotExists<NewsContext>());
}
public DbSet<News> Newss { get; set; }
public DbSet<Category> Categories { get; set; }
}
and my connection string is right below
<connectionStrings>
<add name="NewsContext" connectionString="Data Source=nevra\sqlexpress;Initial Catalog=NewsContext;Integrated Security=True;" providerName="System.Data.SqlClient" />
</connectionStrings>

Related

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>();

Asp Core Multiple Entity Relationships

I am working on modeling a Contact Info Structure and haven't quite figured out how the relationships should be coded with EF Core. I am fairly new to using EF for data access layer.
I want to have a contact model which can contain Website, Phonenumbers, Emails, or Social Info. Then the contact info will be added to several different models. Any suggestions would be helpful, I am not sure how code this One to many with many table relationship or if it is even possible using EF.
Models so far
public class Contact
{
public String Id { get; set; }
public Int32 ContactType { get; set; } //Enum for Website, Phonenumbers, Emails, or Social
public String RecId { get; set; } //FK to multiple Models
public String RecType { get; set; }//Value for which model the RecID is for
public String Name { get; set; }
public String Value { get; set; }
}
public class ContactInfo
{
public virtual IList<Contact> Website { get; set; }
public virtual IList<Contact> PhoneNumbers { get; set; }
public virtual IList<Contact> Emails { get; set; }
public virtual IList<Contact> Socials { get; set; }
}
//Example of models to use the contact model
public class Company
{
....
pubic ContactInfo ContactInfo { get; set;}
}
public class Client
{
....
pubic ContactInfo ContactInfo { get; set;}
}
If I understand your question correctly, then you could use following code sample, but it is not exactly what you are trying to achieve. This may give you some understanding what you need to do with EF.
public class Contact
{
public String Id { get; set; }
public ContactType ContactType { get; set; } //Enum for Website, Phonenumbers, Emails, or Social
public String RecId { get; set; } //FK to multiple Models (This can't be the FK to multiple table as it should be FK for one table so that FK for Company would be CompanyId, FK for the Client should ClientId)
public String RecType { get; set; }//Value for which model the RecID is for (This need to rethink as it may not needed.)
public String Name { get; set; }
public String Value { get; set; }
// One to Many Relationship
public string CompanyId? { get; set; }
public string ClientId? { get; set; }
public Company Company { get; set; }
public Client Client { get; set; }
}
public class Company
{
public String Id { get; set; }
// Other properties
// One to Many Relationship
public ICollection<Contact> Contacts { get; set; }
}
public class Client
{
public String Id { get; set; }
// Other properties
// One to Many Relationship
public ICollection<Contact> Contacts { get; set; }
}
/* Db context */
public class YourDbContext : DbContext
{
public YourDbContext(DbContextOptions<YourDbContext> options)
: base(options)
{
}
public virtual DbSet<Contact> Contacts { get; set; }
public virtual DbSet<Company> Companies { get; set; }
public virtual DbSet<Client> Clients { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Contact>().HasKey(t => t.Id);
modelBuilder.Entity<Company>().HasKey(t => t.Id);
modelBuilder.Entity<Company>().HasMany(c => c.Contacts).WithOne(c => c.Company).HasForeignKey(k => k.CompanyId);
modelBuilder.Entity<Client>().HasKey(t => t.Id);
modelBuilder.Entity<Client>().HasMany(t => t.Contacts).WithOne(c =>c.Client).HasForeignKey(k => k.ClientId);
}
}
/* Db context - Endd */
public enum ContactType
{
Website,
PhoneNumbers,
Emails,
Social
}
Let me know if you need anymore information.
With the help from DSR, this is the solution I have (untested).
public class Company
{
public String Id { get; set; }
public String Name { get; set; }
public ICollection<ContactPhone> PhoneNumbers { get; set; }
public ICollection<ContactEmail> ContactEmail { get; set; }
public ICollection<ContactWebsite> ContactWebsite { get; set; }
public ICollection<ContactSocial> ContactSocial { get; set; }
}
public class Client
{
public String Id { get; set; }
public String Name { get; set; }
public ICollection<ContactPhone> PhoneNumbers { get; set; }
public ICollection<ContactEmail> ContactEmail { get; set; }
public ICollection<ContactWebsite> ContactWebsite { get; set; }
public ICollection<ContactSocial> ContactSocial { get; set; }
}
public class ContactWebsite
{
public String Id { get; set; }
public String Url { get; set; }
public Company Company { get; set; }
public Client Client { get; set; }
}
public class ContactPhone
{
public String Id { get; set; }
public String Type { get; set; }
public String Number { get; set; }
public Company Company { get; set; }
public Client Client { get; set; }
}
public class ContactEmail
{
public String Id { get; set; }
public String Category { get; set; }
public String Email { get; set; }
public Company Company { get; set; }
public Client Client { get; set; }
}
public class ContactSocial
{
public String Id { get; set; }
public String Site { get; set; }
public String Handle { get; set; }
public Company Company { get; set; }
public Client Client { get; set; }
}

How to make changes in Database First code to make it working with Code First

i am having trouble in changing code from database first to code first.I was implementing this blog post http://techbrij.com/facebook-wall-posts-comments-knockout-aspnet-webapi.
First trouble is with database generated from code first.It is creating two User Profile tables in database.First is singular and another is Plurized.
Singular one (UserProfile table)is created while registering(Simple membership used).
My Post class is something like this----
public class Post
{
public Post()
{
this.PostComments = new HashSet<PostComment>();
}
[Key]
public int PostId { get; set; }
public string Message { get; set; }
public int PostedBy { get; set; }
public System.DateTime PostedDate { get; set; }
public int UserId { get; set; }
[ForeignKey("UserId")]
public virtual UserProfile UserProfile { get; set; }
public virtual ICollection<PostComment> PostComments { get; set; }
}
}
and my Post Comment class is something like this----
public class PostComment
{
[Key]
public int CommentId { get; set; }
public int PostId { get; set; }
public string Message { get; set; }
public int CommentedBy { get; set; }
public System.DateTime CommentedDate { get; set; }
public virtual Post Post { get; set; }
public virtual UserProfile UserProfile { get; set; }
}
and my UserProfile class is like this----
public class UserProfile
{
public UserProfile()
{
this.PostComments = new HashSet<PostComment>();
this.Posts = new HashSet<Post>();
}
[Key]
public int UserId { get; set; }
public string UserName { get; set; }
public string AvatarExt { get; set; }
public virtual ICollection<PostComment> PostComments { get; set; }
public virtual ICollection<Post> Posts { get; set; }
}
and My DbContext is something like this---
public class WallEntitiesDbContext : DbContext
{
public WallEntitiesDbContext():base("WallEntitiesDbContext")
{
}
public DbSet<PostComment> PostComments { get; set; }
public DbSet<Post> Posts { get; set; }
public DbSet<UserProfile> UserProfiles { get; set; }
public override int SaveChanges()
{
return base.SaveChanges();
}
}
and my connection string are like this----
<add name="DefaultConnection" connectionString="Data Source=.;Initial Catalog=DBWallPostByTechBrij;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
what changes should i made so that only one UserProfile table is created in database and WallEntitiesDbContext should be able to retreive information from that table in database.
Right now, If i remove------
DbSet<UserProfile> UserProfiles {get; set;}
then i start getting error in my wallpostController. If anyone could help me in getting this working with code First then it would be great help.One more thing,I have manually entered some sample data into database so, after login it should show posts and comments from database but it's not showing and if i tried to post something, it throws exception System.Data.Infrastructure.DbUpdateException at this line----
public override int SaveChanges()
{
return base.SaveChanges();
}
in WallEntitiesDbContext class.
Plzzz anyone have a look it.What changes should i make to make it working.
I think there is no need for two dbContext as u are implementing from the article.
So, use only one dbcontext like this----
public class UsersContext : DbContext
{
public UsersContext()
: base("DefaultConnection")
{
}
public DbSet<UserProfile> UserProfile { get; set; }
public DbSet<Post> Posts { get; set; }
public DbSet<PostComment> PostComments { get; set; }
In DbFisrt approach as in article, u may use it but in code first approach, definitly two dbcontext will create two userProfile table.
Nothing more is needed to be changed.

How to create a history model of a specific model on 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.

Custom simple membership provider adding row

I have a custom SimpleMembershipProvider and i have defined all tables that the SimpleMembershipProvider requires, like webpages_Membership:
[Table("webpages_Membership")]
public class Membership
{
public Membership()
{
Roles = new List<Role>();
OAuthMemberships = new List<OAuthMembership>();
}
[Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
public int UserId { get; set; }
public DateTime? CreateDate { get; set; }
[StringLength(128)]
public string ConfirmationToken { get; set; }
public bool? IsConfirmed { get; set; }
public DateTime? LastPasswordFailureDate { get; set; }
public int PasswordFailuresSinceLastSuccess { get; set; }
[Required, StringLength(128)]
public string Password { get; set; }
public DateTime? PasswordChangedDate { get; set; }
[Required, StringLength(128)]
public string PasswordSalt { get; set; }
[StringLength(128)]
public string PasswordVerificationToken { get; set; }
public DateTime? PasswordVerificationTokenExpirationDate { get; set; }
public ICollection<Role> Roles { get; set; }
[ForeignKey("UserId")]
public ICollection<OAuthMembership> OAuthMemberships { get; set; }
}
But how do i add a record in this table within the Seed() method in the configuration.cs file that migrations creates when enabled?
Assuming you have the custom membership provider correctly configured in the web.config you should be able to add a record in the Seed method by doing this.
var membership = (MyMembershipNamespace.SimpleMembershipProvider)Membership.Provider;
membership.CreateUserAndAccount("test", "password");