.NET Core Entity Framework how to map nested class into one sql table - sqlite

I'm still new to .NET Core. I have this character that I want to store in SQLite using an entity.
But by default, Character, CharacterData and CharacterLine are mapped to different tables.
Is there anyways to make entity map them to the same table?
public class Character
{
public int CharacterID { get; set; }
public string characterName { get; set; }
public string characterDisplayName { get; set; }
public string characterIconPath { get; set; }
public CharacterData characterInfo { get; set; }
}
public class CharacterData
{
public int CharacterDataID { get; set; }
public Gender Gender { get; set; }
public int Height { get; set; }
public DateTime BirthDay { get; set; }
public CharacterLine lines { get; set; }
}
public class CharacterLine
{
public int CharacterLineID { get; set; }
public string line1 { get; set; }
public string line2 { get; set; }
public string line3 { get; set; }
public string line4 { get; set; }
}

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

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?

EF6 MVC5 Setting a 1-1 Relationship

I have got my application up and running using Code first, I am trying to set a 1-1 relationship but when I update-database I get the error "SupplyPointId: Name: Each property name in a type must be unique. Property name 'SupplyPointId' is already defined."
I've tried removing the existing index constraint on SupplyPointAddress.SupplyPointId and that does not help. In the other table its the PK. Any comments really appreciated
public partial class SupplyPoint
{
[Key]
//[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int SupplyPointId { get; set; }
public string SPID { get; set; }
public string SupplyPointName { get; set; }
public int SupplyPointTypeId { get; set; }
public DateTime SupplyPointEffectiveDateTime { get; set; }
public string GazateerRef { get; set; }
public virtual SupplyPointType SupplyPointType { get; set; }
//[ForeignKey("SupplyPointId")]
public virtual SupplyPointAddress SupplyPointAddress { get; set; }
}
public partial class SupplyPointAddress
{
[Key]
//[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int SupplyPointAddressId { get; set; }
public int SupplyPointId { get; set; }
public string D5001_FreeDescriptor { get; set; }
public string D5002_SubBuildingName { get; set; }
public string D5003_BuildingName { get; set; }
public string D5004_BuildingNumber { get; set; }
public string D5005_DependentThoroughfareName { get; set; }
public string D5006_DependentThoroughfareDescriptor { get; set; }
public string D5007_ThoroughfareName { get; set; }
public string D5008_ThoroughfareDescriptor { get; set; }
public string D5009_DoubleDependentLocality { get; set; }
public string D5010_DependentLocality { get; set; }
public string D5011_PostTown { get; set; }
public string D5012_County { get; set; }
public string D5013_Postcode { get; set; }
public virtual SupplyPoint SupplyPoint { get; set; }
}
public System.Data.Entity.DbSet<AscendancyCF.Models.SupplyPoint> SupplyPoints { get; set; }
public System.Data.Entity.DbSet<AscendancyCF.Models.SupplyPointAddress> SupplyPointAddresses { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<SupplyPointAddress>()
.HasOptional<SupplyPoint>(u => u.SupplyPoint)
.WithRequired(c => c.SupplyPointAddress).Map(p => p.MapKey("SupplyPointId"));
base.OnModelCreating(modelBuilder);
}
I moved the foreign key into SupplyPoint table so that the foreign key was being defined as SupplyPointAddressId in SupplyPoint. This worked and allows me to do SupplyPoint.SupplyPointAddress in resultant model
Since you're testing with a real DB. Use some of the
Database Initialization Strategies in Code-First:
public class SchoolDBContext: DbContext
{
public SchoolDBContext(): base("SchoolDBConnectionString")
{
Database.SetInitializer<SchoolDBContext>(new CreateDatabaseIfNotExists<SchoolDBContext>());
//Database.SetInitializer<SchoolDBContext>(new DropCreateDatabaseIfModelChanges<SchoolDBContext>());
//Database.SetInitializer<SchoolDBContext>(new DropCreateDatabaseAlways<SchoolDBContext>());
//Database.SetInitializer<SchoolDBContext>(new SchoolDBInitializer());
}
public DbSet<Student> Students { get; set; }
public DbSet<Standard> Standards { get; set; }
}
(Excerpt from this site)
It is pretty self explanatory.
If there's already a DB created, it just DROPs it.
Happy coding!

MVC4 EF5 entity property not updating on SaveChanges()

I've been reading through lots of articles trying to learn MVC4, but I'm stumped as to why my entity is not getting updated to database.
I've been trying to modify the MVC4 VS2012 Internet template.
So, here's the Controller action:
[HttpPost, ActionName("Approve")]
[Authorize]
public ActionResult ApproveConfirmed(long id)
{
using (StudentiContext context = new StudentiContext())
{
// context.Configuration.AutoDetectChangesEnabled = false;
var studente = (from d in context.STUDENTI_STRANIERI_MASTER_REG
where d.ID_PERSONA == id
select d).Single();
STUDENTI_STRANIERI_MASTER_REG st2 = studente;
st2.ESITO = 1;
//studente.ESITO = 1;
var statos = context.Entry(studente).State;
Console.WriteLine("Before DetectChanges: {0}",statos);
//context.ChangeTracker.DetectChanges();
context.Entry(studente).State = EntityState.Modified;
context.Entry(studente).CurrentValues.SetValues(st2);
// var tracked = context.ChangeTracker.Entries();
context.Entry(studente).Property( o => o.ESITO ).IsModified = true;
TryUpdateModel(studente);
context.SaveChanges();
Console.WriteLine("After DetectChanges: {0}",statos);
return RedirectToAction("PrivateIndex");
}
}
The aim is just to update one property, ESITO and set it to 1. Currently its value is 2.
This is the model:
namespace MvcStudenti2.Models
{
using System;
using System.Collections.Generic;
public partial class STUDENTI_STRANIERI_MASTER_REG
{
public long ID_PERSONA { get; set; }
public string COGNOME { get; set; }
public string NOME { get; set; }
public string SESSO { get; set; }
public System.DateTime DATA_NASCITA { get; set; }
public long ID_STATO_NASCITA { get; set; }
public string LUOGO_NASCITA_ESTERO { get; set; }
public string CODICE_FISCALE { get; set; }
public string TITOLO_POSSEDUTO { get; set; }
public Nullable<short> DURATA_TITOLO { get; set; }
public string VOTAZIONE { get; set; }
public string UNI_PROVENIENZA { get; set; }
public long ID_STATO_UNI { get; set; }
public string CERT_LINGUISTICA { get; set; }
public string CERT_PUNTEGGIO { get; set; }
public string NOTE { get; set; }
public System.DateTime DATA_RICHIESTA { get; set; }
public short ESITO { get; set; }
public string CDS_COD { get; set; }
public string EMAIL { get; set; }
public string NUMERO_TELEFONO { get; set; }
public string INDIRIZZO { get; set; }
public string CAP_INDIRIZZO { get; set; }
public string CITTA { get; set; }
public long ID_STATO_INDIRIZZO { get; set; }
public string DESCRIZIONE_CIT_NAZ { get; set; }
public Nullable<System.DateTime> DATA_COMPLETAMENTO_ATTESO { get; set; }
public Nullable<System.DateTime> ANNO_COMPLETAMENTO { get; set; }
public Nullable<short> DURATA_CORSO_COMPLETATO { get; set; }
public decimal GPA { get; set; }
public string ALTRI_TITOLI { get; set; }
public string MADRELINGUA { get; set; }
public Nullable<short> CERT_TOEFL_PUNT { get; set; }
public string CERT_FIRSTCERT_GRADE { get; set; }
public Nullable<short> CERT_FIRSTCERT_PUNT { get; set; }
public byte[] FILE_CV { get; set; }
public byte[] FILE_CARRIERA { get; set; }
public byte[] FILE_CERT_LINGUA { get; set; }
public byte[] FILE_DOC_IDENTITA { get; set; }
public string PWD { get; set; }
public string FILE_CV_NOME { get; set; }
public string FILE_CARRIERA_NOME { get; set; }
public string FILE_CERT_LINGUA_NOME { get; set; }
public string FILE_DOC_IDENTITA_NOME { get; set; }
public string FILE_CV_TIPO { get; set; }
public string FILE_CARRIERA_TIPO { get; set; }
public string FILE_CERT_LINGUA_TIPO { get; set; }
public string FILE_DOC_IDENTITA_TIPO { get; set; }
public Nullable<short> STATO { get; set; }
public Nullable<short> VALUTATO { get; set; }
public Nullable<short> ARCHIVIATO { get; set; }
public string CDS_COD_2 { get; set; }
public Nullable<short> MAIL_INVIATA { get; set; }
public string LINK_ULTIMO_CORSO { get; set; }
public Nullable<short> ATTIVO { get; set; }
public byte[] FILE_LETTERA_ACCETTAZIONE { get; set; }
public string FILE_LETTERA_ACCETTAZIONE_NOME { get; set; }
public string FILE_LETTERA_ACCETTAZIONE_TIPO { get; set; }
}
}
Everywhere I read I find that SaveChanges() should be enough, possibly after the EntityState.Modified.
I can correctly edit the entity, if I pass the whole entity to the Action, but in this case the Approve view is a built on a Detail template, so I don't have anything to POST from it (and I'd prefer not to: I could insert a hidden field and post just that, but I'm trying to update a single filed from code, and I'm not sure if the whole entity would get updated or overwritten ).
statos goes to "modified", if I understand correctly, because I have done a query on the entity.
Another thing I don't understand is why ESITO gets update -also- in studente, but then reverts to "2" after SaveChanges().
Are property changes being detected? I've wrapped every Action in a using block, as suggested elsewhere, so not to have multiple contextx/instances around.
Could anyone please point me to what I'm doing wrong? The code above is probably over-redundant, but I've been trying everything I have found on SO.
Thanks, everyone.
The following is all that is required to change the ESITO property.
[HttpPost, ActionName("Approve")]
[Authorize]
public ActionResult ApproveConfirmed(long id)
{
using (StudentiContext context = new StudentiContext())
{
// context.Configuration.AutoDetectChangesEnabled = false;
var studente = (from d in context.STUDENTI_STRANIERI_MASTER_REG
where d.ID_PERSONA == id
select d).Single();
studente.ESITO = 1;
context.SaveChanges();
return RedirectToAction("PrivateIndex");
}
}

Resources