简体   繁体   中英

LINQ to sql insert data c#

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.

Are you using a local database file (eg 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?

嗨使用时间戳数据类型。我认为问题将得到解决。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM