简体   繁体   English

在LINQ to SQL中执行查询

[英]Executing Queries in LINQ to SQL

How do I execute a query using LINQ to SQL? 如何使用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 ? 如何使用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 Student object, add a StudentLoan to its StudentLoans collection, and add the Student to the Context.Students collection with myContextInstance.Students.InsertOnSubmit(newStudent) and write out the changes with a call to myContextInstance.SubmitChanges . 假设您已将所有表拖到Linq2Sql设计器上,只需创建一个Student对象,将StudentLoan添加到其StudentLoans集合中,然后使用myContextInstance.Students.InsertOnSubmit(newStudent)Student添加到Context.Students集合中并写出通过调用myContextInstance.SubmitChanges更改。

So, putting it all together: 所以,把它们放在一起:

using(var myContextInstance=new YourContext())
{
    var student = new Student(){Name = "user962206"};
    var studentLoan = new StudentLoan(){Amount = 50000};
    student.StudentLoans.Add(studentLoan);
    myContextInstance.Students.InsertOnSubmit(student);
    myContextInstance.SubmitChanges();
}

The code snippet works if your DataContext looks like this: 如果您的DataContext看起来像这样,代码片段就有效:

在此输入图像描述

This is the result of just dragging your tables to the design surface of the dbml file. 这是将表拖动到dbml文件的设计图面的结果。

If by your question you mean "how do a execute a raw SQL query with LINQ to SQL," then look at the ExecuteCommand and ExecuteQuery methods: 如果您的问题意味着“如何使用LINQ to SQL执行原始SQL查询”,那么请查看ExecuteCommandExecuteQuery方法:

All these methods take a raw SQL query, like yours, and runs it against the database 所有这些方法都采用原始SQL查询,就像您的查询一样,并针对数据库运行它

If you meant by your question "how do I write this SQL query as a LINQ query" then please clarify your question. 如果您的问题是“如何将此SQL查询编写为LINQ查询”,请澄清您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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