I am struggling with the concept of code first entities, and data annotations.
I am trying to create a database which among others has a People table and an ensemble table which are linked by a one to many relationship as in each ensemble can have many people.
how exactly do I set up these classes to simulate a one to many relationship and more importantly how do I add data to each table.
I have tried the following:
//Ensemble entity class
public class Ensemble
{
[Key]
public int ensembleID { get; set; }
public string ensembleName { get; set; }
public virtual List<People> persons { get; set; }
public Ensemble (int ensembleID, string ensembleName)
{
this.ensembleID = ensembleID;
this.ensembleName = ensembleName;
}
}
// people entity class
public class People
{
[Key]
public int personID { get; set; }
[Required]
public string firstname { get; set; }
[Required]
public string surname { get; set; }
[Required]
public DateTime birthDate { get; set; }
public string cellphone { get; set; }
public string email { get; set; }
public bool inSchool { get; set; } // Are they currently in a primary or secondary school
public int ensembleID { get; set; }
//[ForeignKey("ensembleID")]
public Ensemble Ensemble { get; set; }
public People(int personID, string firstname, string surname, DateTime birthDate, string cellphone, string email, bool inSchool, int ensembleID)
{
this.personID = personID;
this.firstname = firstname;
this.surname = surname;
this.birthDate = birthDate;
this.cellphone = cellphone;
this.email = email;
this.inSchool = inSchool;
this.ensembleID = ensembleID;
}
// Adding data
context.People.Add(new People(1, "Adam", "Herd", new DateTime(1992, 3, 12), "0274578956", "adamherd1@live.com", true));
context.Ensemble.Add(new Ensemble(1, "Little River Band"));
However this returns an error. 'The INSERT statement conflicted with the FOREIGN KEY constraint \\"FK_dbo.People_dbo.Ensembles_ensembleID\\". The conflict occurred in database \\"SMMC_adam_stacy.Context\\", table \\"dbo.Ensembles\\", column 'ensembleID'.\\r\\nThe statement has been terminated."}'
Code snippets of how to do this correctly would be obliged as would furthur explanation of how navigation properites work eg public Virtual Ensemble Ensemble { get; set; }
context.Ensemble.Add(new Ensemble(1, "Little River Band"));
context.People.Add(new People(1, "Adam", "Herd", new DateTime(1992, 3, 12), "0274578956", "adamherd1@live.com", true));
Add people to the collection in Ensemble
:
var ens = new Ensemble(1, "Little River Band");
var person = new People(1, "Adam", "Herd", new DateTime(1992, 3, 12),
"0274578956", "adamherd1@live.com", true));
// BTW: the constructor does not match the call
ens.persons.Add(person);
context.Ensemble.Add(ens);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.