LAST EDIT:
There were various problems with my code, which are explained in the comments of two answers. In the end i've used the following code:
using (var context = new CijferDBEntities())
{
context.Student.Add(newStudent);
try
{
context.SaveChanges();
}
catch (DbEntityValidationException ex)
{
foreach (var entityValidationErrors in ex.EntityValidationErrors)
{
foreach (var validationError in entityValidationErrors.ValidationErrors)
{
Console.Write("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
}
}
}
}
EDIT: I've explained this badly, I'd like to know how I would insert a new student (which I created here) into the table dbo.Student
.
I'd like to insert a new row into my table in the database using C#.
First have I defined a student here:
private void btnToevoegen_Click(object sender, EventArgs e)
{
EntityVoorbeeld vb = new EntityVoorbeeld();
string Roepnaam = txtRoepnaam.Text;
string Voegsel = txtVoegsel.Text;
string Achternaam = txtAchternaam.Text;
DateTime Geboortedatum = Convert.ToDateTime(txtGeboortedatum.Text);
string Adres = txtAdres.Text;
string Postcode = txtPostcode.Text;
string Woonplaats = txtWoonplaats.Text;
string Email = txtEmail.Text;
string Telefoon = txtTelefoon.Text;
string Mobiel = txtMobiel.Text;
// Create new student
Student newStudent = new Student();
newStudent.Roepnaam = Roepnaam;
newStudent.voegsel = Voegsel;
newStudent.Achternaam = Achternaam;
newStudent.Geboortedatum = Geboortedatum;
newStudent.Adres = Adres;
newStudent.Postcode = Postcode;
newStudent.Woonplaats = Woonplaats;
newStudent.Email = Email;
newStudent.Telefoon = Telefoon;
newStudent.Mobiel = Mobiel;
// Add student to table
vb.Studenten.add(newStudent);
vb.SaveChanges();
}
which I want to be inserted into the table once the button is clicked.
I have used the following code to fetch the students from the database:
public ObservableCollection<Student> Studenten(string klas, string schooljaar)
{
Lesgroep groep = ce.Lesgroep.SingleOrDefault(g => g.Naam == klas && g.Schooljaar == schooljaar);
return new ObservableCollection<Student>(groep.Student.OrderBy(s => s.Achternaam).ThenBy(s => s.Roepnaam));
}
At this code:
vb.Studenten.add(newStudent);
i get the following error upon hovering over Studenten
'CijferDB.EntityVoorbeeld.Studenten(string, string)' is a 'method', which is not valid in the given context.
Turned out my DBSet was missing, i edited in the following:
public DbSet<Student> Students { get; set; }