开发者

LINQ to sql insert data c#

开发者 https://www.devze.com 2023-01-18 21:15 出处:网络
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

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开发者_如何学C 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.


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.


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


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?


Hi use timestamp data type.I think problem will be solved.

0

精彩评论

暂无评论...
验证码 换一张
取 消