views:

43

answers:

3

I have created one function whose purpose is to add data to database (I'm using linq to sql)

This is the code I have written

       public static void Add(string Name, int Quantitty) {

        DataDataContext Database = new DataDataContext();
        tests test = new tests();

        test.Name = Name;
        test.Quantity = (short)Quantitty;

        Database.tests.InsertOnSubmit(test);

        Database.SubmitChanges();
    }

I have opened my application, pressed the button which calls this function and closed application, than I have opened table data in VS and there was no data in database.

I dont understand what I'm doing wrong.

A: 

have you stepped through in debug mode to see if you have any errors? by the way you should probably have a using statement and a try catch in there maybe?

edit to add a code example

this will show if an exception is raised in the SubmitChanges, also the using makes sure the dispose is called

using(var Database = new DataDataContext())
 {
    tests test = new tests();

    test.Name = Name;
    test.Quantity = (short)Quantitty;

    Database.tests.InsertOnSubmit(test);
    try
    {
        Database.SubmitChanges();
    }
    catch (ChangeConflictException e)
    {
        //report error, log error whatever...
    }
}
Pharabus
A: 

1- Use try, catch.

2- Which one is Primary Key? You cannot make insert without primary key (or table must have primaray key)

3- Did you debug your code?

Serkan Hekimoglu
Yea it has Primary key the problem is that I dont know how to add it as I have selected it to be increased by one by itself, yeas I have debug my code
dnsau
so I recommend using try catch, and lets see what will happen.
Serkan Hekimoglu
nothing happens, everything same as before
dnsau
have you tried using SQL Profiler to capture what SQL statement (if any) is being sent from Linq to the DB?
jules
A: 

Are you using a local database file (e.g. Database1.sdf)? If this is the case, the database gets copied to the bin folder when you build your app, which then uses that copy. The application is adding data to a different file than the one VS is opening.

Garrett
Nope, i'm using service-based database (.mdf)
dnsau
Service-based databases also get copied to the output folder. Try attaching VS to the mdf file in bin/debug where you're running your app and see if the data ends up in that one.
Garrett
yep :) it works ty
dnsau