0

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; }
Wessah
  • 101
  • 13

3 Answers3

0

Perhaps there is a violation of constraint , ensure that there is not violation of primary key

0

To summarize:

  1. It turns out that OP encounter DbEntityValidationException which is cause by one of the model field being null when inserting to database.

  2. The DBSet Student that OP include in previous code is also causing the newStudent instance to not insert into database as he was not referring to his DbContext class, rather EntityVoorbeeld, a normal class which does not contain the DbSet Student.

Shawn Yan
  • 183
  • 8
  • The connection is working fine since i'm already fetching a ObservableCollection of Students, i have edited the post. – Wessah Jun 06 '16 at 08:21
  • can you post your dbcontext class? i think the problem is that your are adding to the wrong dbset – Shawn Yan Jun 06 '16 at 08:39
  • @Wessah I'd read the comments on your post and it seems that you have encountered a DbEntityValidationException. Try to find out what causes the exception then only you can add student to database. – Shawn Yan Jun 06 '16 at 14:46
  • So i've debugged my code and found the following: It does not fill newStudent with the inserted data, but instead fills 'this' with all the data. [Here's a picture for reference](http://imgur.com/xnSxMoU) – Wessah Jun 07 '16 at 09:33
  • Check whether all your strings variable have values because I only see string Mobiel with value of "d". The "this" is normal to have as it refers to itself when running code . – Shawn Yan Jun 07 '16 at 09:57
  • All strings variables have values, it just only displays the last one (which is mobiel). Why would newStudent be null though? – Wessah Jun 07 '16 at 10:27
  • Ok i've read a bit more.. turns out it does insert the student locally, but still won't save the changes because of the DbEntityValidationException, which i think could be the ID being 0, it having no lesgroep, no resultaat or no studentcode[here's 3 screenshots](http://imgur.com/a/3YE9q) – Wessah Jun 07 '16 at 10:41
  • I agree with @Jcl about looking into DbEntityValidation exception , you can show the exact error with the code provided by Romias in [here](http://stackoverflow.com/questions/21606454/how-to-handle-system-data-entity-validation-dbentityvalidationexception) – Shawn Yan Jun 07 '16 at 12:29
  • I've seen that, but how do i make a seperate class? I can't just right click it and add a class.. – Wessah Jun 07 '16 at 12:34
  • no need to add class, just put the whole **public override int saveChanges(){.....}** into your CijferDBEntities class – Shawn Yan Jun 07 '16 at 12:39
  • This did it! I'll post the solution in the OP. It turned out that StudentCode was missing after all.. Thanks for your patience with me, i learned a lot these last days! – Wessah Jun 07 '16 at 12:52
  • NP glad to help out :-) – Shawn Yan Jun 07 '16 at 13:13
  • btw can you post your own answer as accepted answer? this can help future readers not to get confuse by our long comments. Cheers~ :-) – Shawn Yan Jun 07 '16 at 13:15
  • I've edited in my own answer on top of the post, but since our exchange was pretty long with various problems i think it's better to keep it this way, no? – Wessah Jun 07 '16 at 13:16
  • At least edit this answer with the valid one. As it is now, the "accepted answer" does not pose an answer to the original question. This might be ok now, but future readers will definitely be confused by this answer being accepted. Anyway, this question was TONS of questions indeed and it has been edited error after error. If it was me, I'd delete the question alltogether, because neither the question nor the answers make sense anymore – Jcl Jun 07 '16 at 20:05
0

Studenten is a method (which you are showing on your question). For adding a new entity you need to add it to your context's DbSet, not to a method that returns an ObservableCollection.

Your DbContext (by your code, the type EntityVoorbeeld) will have a DbSet property of type Student (with a name, that you are not providing). Use that name to add it:

vb.TheNameOfTheStudentDbSet.Add(newStudent);
vb.SaveChanges();

In English, that'd more likely be called Students, so your EntityVoorbeeld class would look something like:

public class EntityVoorbeeld : DbContext
{
   public DbSet<Student> Students { get; set; }     

   /* 
      ... the rest of your context's properties and methods ...
   */
}

But your names may vary.

Jcl
  • 27,696
  • 5
  • 61
  • 92
  • It turns out i did not have the DBSet in there at all, i've inserted it now (see the bottom of OP) but vb.Students.add(newStudent); won't work yet because DBSet contains no definition for 'Add'. – Wessah Jun 06 '16 at 08:57
  • @Wessah use title case (`Add`, not `add`). C# is case sensitive. [DbSet definitely has `Add`](https://msdn.microsoft.com/es-es/library/system.data.entity.dbset.add(v=vs.113).aspx) – Jcl Jun 06 '16 at 08:58
  • Thanks, errors are gone but i get an expection telling me the connection doesn't work/the dbcontext is incorrect. Should i send a pastebin? – Wessah Jun 06 '16 at 09:31
  • I'd say that should be a completely different question, but just in case it's a trivial error, paste the pastebin's link to code in the comments (not in the question, by any means) – Jcl Jun 06 '16 at 09:32
  • Seems your `EntityVoorbeeId` is not the `DbContext`: did you just randomly add that? It looks like a repository. Your `DbContext` is `CijferDBEntities`, which you access from `EntityVoorbeeId` using the variable `ce`. You should add the `DbSet` property to `CijferDBEntities` – Jcl Jun 06 '16 at 09:40
  • (I'm trying to understand it without understanding the variable names or comments, which is a bit hard, but it looks like that on your code) – Jcl Jun 06 '16 at 09:40
  • So i've checked the definition of CijferDBEntities and it leads to CijferModel.Context.cs which looks like this http://pastebin.com/Y4mDcSXJ – Wessah Jun 06 '16 at 09:48
  • So you already got your `Student` there. The minimum to add your student would be `using(var context = new CijferDBEntities()) { context.Student.Add(newStudent); context.SaveChanges(); }` – Jcl Jun 06 '16 at 09:49
  • 1
    Of course, you should have methods in your repository to add a student if you are working using that pattern... but that's WAY outside the realm of this question (and probably for StackOverflow, unless you have *specific* questions, not just general "how-to" ones). Try to understand what your code is doing, do not randomly add this and that to see if it compiles and works :-) – Jcl Jun 06 '16 at 09:50
  • Yeah i understand what you're saying and i try to not randomly add things but i would really like to get this working asap, i'm still a student so i'll eventually get the logic behind it, it just takes some time. So i figured i may have to create a method in `EntityVoorbeeld` to add the `NewStudent` into the table from there(as you can see the SaveChanges method is already there). I don't know how i'd create this method though, and if this is really the best way or fastest to do it. – Wessah Jun 06 '16 at 13:49
  • The method could be as simple as my last comment – Jcl Jun 06 '16 at 13:50
  • The method you wrote should be placed under where i defined NewStudent, right? Because when i tried that, i got the following on `context.SaveChanges();`: `An unhandled exception of type 'System.Data.Entity.Validation.DbEntityValidationException' occurred in EntityFramework.dll Additional information: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.` – Wessah Jun 06 '16 at 13:59
  • 1
    That's again a completely different error. More likely some fields of the new student are wrong (invalid data or required data not entered, etc.) . The details of the exception should tell you what's wrong – Jcl Jun 06 '16 at 16:36
  • So i don't know how i link comments but i've commented this to the other answer – Wessah Jun 07 '16 at 09:42
  • @Wessah can we see the code of the `Student` class, and the code of the `CijferDBEntities` one? There you can probably see the validation constraints. ID being 0 *should* be no problem (it gets autogenerated), but there could be other constraints you are not filling properly – Jcl Jun 07 '16 at 11:00
  • Doesn't look like there's any restriction or validation there. If it's a model-first (it looks like so), then there might be restrictions there. A careful study of the `DbEntityValidation` exception should give the cause(s) of the entity (the student) being "rejected" – Jcl Jun 07 '16 at 11:26
  • Check the comments with, @Shawn Yan, there should be more explanation there – Wessah Jun 07 '16 at 11:39