Click here to Skip to main content
15,899,126 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm trying to do dml operations on Linq by ExecuteQuery() and ExecuteCommand(). The error that occurred is after execution it doesn't affects the record in database.
For eg: To insert a new record to table in database, I used ExecuteCommand().

After the error occurred i coded with Submitchanges() but there is no result of what i expect.

A Sample code for inserting data to a table:
C#
using(StudentsDbDataContext StudentContext = new StudentsDbDataContext())
{
                int r = StudentContext.ExecuteCommand("insert into tblStudents values ({0},{1},{2})", firstname, lastname, gender);
                if (r > 0) {
                    Console.WriteLine("{0} row added.", r);
                    Console.ReadKey();
                }
            }


What I have tried:

C#
using(StudentsDbDataContext StudentContext = new StudentsDbDataContext())
{
                int r = StudentContext.ExecuteCommand("insert into tblStudents values ({0},{1},{2})", firstname, lastname, gender);
                StudentContext.SubmitChanges();//<--- ADDED
                if (r > 0) {
                    Console.WriteLine("{0} row added.", r);
                    Console.ReadKey();
                }
            }

How to solve this?
Posted
Updated 23-Jan-17 19:12pm
Comments
Andy Lanng 23-Jan-17 11:05am    
Is this just a really cut down version of your code?
If not then why not use the L2S object insert method?
cgprakash 23-Jan-17 12:27pm    
thanks for reply, but i need to do with sql queries using linq methods.
Andy Lanng 23-Jan-17 12:33pm    
In that case I think there must be some sort of race condition. Look at the second query: You set r to be the result of the ExecuteCommand, yet it only has a value after you submit changes. There is no await or async style code I can see on your end.
Try adding Thread.Sleep(100); in place of db.SubmitChanges(). If that works then there is some (odd) race condition.

Try writing it like this (pseudo code):
int r;
using (db){
..r = ExecuteCommand("text");
}
if(r>0)
..do stuff

That way you know r will have returned because it must complete the query before disposing of the context.
cgprakash 26-Jan-17 0:34am    
i have done it already at the earliest but it doesn't affects.

1 solution

Try with below code, may be it help you

C#
StudentContext.Database.SqlQuery<int>("insertProcedure param1 param2 param3");
 
Share this answer
 
Comments
cgprakash 26-Jan-17 0:48am    
Thanks for reply Gopal, I didn't get the property "SqlQuery<int>". What to do?
Gopal Rakhal 26-Jan-17 2:00am    
It is property of EF.
https://msdn.microsoft.com/en-us/library/jj592907(v=vs.113).aspx

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900