溫馨提示×

linq sql語句怎樣改

sql
小樊
81
2024-10-20 06:47:26
欄目: 云計算

在LINQ中,你可以使用SQL類似的語法來查詢數(shù)據(jù)。以下是一個簡單的示例,展示了如何在C#中使用LINQ查詢數(shù)據(jù)庫中的數(shù)據(jù)。

首先,假設(shè)你有一個名為customers的表,其結(jié)構(gòu)如下:

CREATE TABLE customers (
    id INT PRIMARY KEY,
    name VARCHAR(255),
    age INT,
    city VARCHAR(255)
);

然后,你可以使用以下C#代碼來查詢這個表中的數(shù)據(jù):

using System;
using System.Linq;
using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        // 連接到數(shù)據(jù)庫
        string connectionString = "your_connection_string_here";
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();

            // 編寫LINQ查詢
            var query = from c in connection.GetTable<Customer>()
                        where c.age > 30 && c.city == "New York"
                        select c;

            // 執(zhí)行查詢并輸出結(jié)果
            foreach (var customer in query)
            {
                Console.WriteLine($"ID: {customer.id}, Name: {customer.name}, Age: {customer.age}, City: {customer.city}");
            }
        }
    }
}

// 定義Customer類以匹配表結(jié)構(gòu)
public class Customer
{
    public int id { get; set; }
    public string name { get; set; }
    public int age { get; set; }
    public string city { get; set; }
}

在這個示例中,我們使用了LINQ的from子句來指定要查詢的表(通過connection.GetTable<Customer>()獲?。?,并使用where子句來添加過濾條件。最后,我們使用select子句來選擇要返回的字段。

請注意,你需要將your_connection_string_here替換為實際的數(shù)據(jù)庫連接字符串。此外,你可能需要根據(jù)實際的表結(jié)構(gòu)和字段類型調(diào)整Customer類的定義。

0