How do I execute a query using LINQ to SQL? a query that something goes like this.
Let’s say I have this table
CREATE TABLE dbo.Students
(
StudentID INT IDENTITY(1,1) PRIMARY KEY,
Name SYSNAME
);
CREATE TABLE dbo.StudentLoans
(
LoanID INT IDENTITY(1,1) PRIMARY KEY,
StudentID INT FOREIGN KEY REFERENCES dbo.Students(StudentID),
Amount BIGINT -- just being funny
);
Then I wanted to execute this query.
DECLARE
@Name SYSNAME = N'user962206',
@LoanAmount BIGINT = 50000,
@StudentID INT;
INSERT dbo.Students(Name)
SELECT @Name;
SELECT @StudentID = SCOPE_IDENTITY();
INSERT dbo.StudentLoans(StudentID, Amount)
SELECT @StudentID, @LoanAmount;
Is that possible? even if your Rows and Columns are mapped? how can I execute that query with LINQ to SQL ?
It’s been a while, but wouldn’t it be something like this?
Assuming you’ve dragged all your tables onto the Linq2Sql designer, simply create a
Studentobject, add aStudentLoanto itsStudentLoanscollection, and add theStudentto theContext.Studentscollection withmyContextInstance.Students.InsertOnSubmit(newStudent)and write out the changes with a call tomyContextInstance.SubmitChanges.So, putting it all together:
The code snippet works if your DataContext looks like this:
This is the result of just dragging your tables to the design surface of the dbml file.