C# LINQ to SQL查询数据库

5 篇文章 1 订阅

LINQ提供了查询表达式,它使用SQL风格的语句执行查询并生成结果集。然后,可以遍历这个结果集并进行相应的处理。为了使用LINQ,被查询的对象必须是"可枚举"的,它们必须实现了IEnumerable接口的集合。LINQ to SQL能根据你定义的类创建它自己的可枚举对象集合,这些类直接映射到数据库中的表,它们称为实体类。DataContext类负责实体类与数据库中表的关系,DataContext对象能自动控制数据库连接。

SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = "(local)";// ".\\MSSQLSERVER";
builder.InitialCatalog = "Northwind";
builder.IntegratedSecurity = true;
Northwind northwindDB = new Northwind(builder.ConnectionString);
try
{
    Console.WriteLine("Please enter a customer ID(5 characters):");
    string customerId = Console.ReadLine();
    var ordersQuery = from o in northwindDB.Orders where String.Equals(o.CustomerID, customerId) select o;
    foreach(var order in ordersQuery)
    {
        if (order.ShippedDate == null)
        {
            Console.WriteLine("Order {0} not yet shipped\n\n", order.OrderID);
        }
        else
        {
            Console.WriteLine("Order: {0}\nPlaced:{1}\nShipped: {2}\n" +
                "To Address: {3}\n{4}\n{5}\n{6}\n\n", order.OrderID, order.OrderDate, order.ShippedDate,
                order.ShipName,order.ShipAddress, order.ShipCity, order.ShipCountry);
        }
    }
    Console.ReadLine();
}
catch (Exception ex)
{
    Console.WriteLine("Error accessing the database: {0}", ex.Message);
    Console.ReadLine();
}


[Table(Name ="Orders")]
public class Order
{
    [Column(IsPrimaryKey =true,CanBeNull =false)]
    public int OrderID { get; set; }
    [Column]
    public string CustomerID { get; set; }
    [Column]
    public DateTime? OrderDate { get; set; }
    [Column]
    public DateTime? ShippedDate { get; set; }
    [Column]
    public string ShipName { get; set; }
    [Column]
    public string ShipAddress { get; set; }
    [Column]
    public string ShipCity { get; set; }
    [Column]
    public string ShipCountry { get; set; }
}
public class Northwind : DataContext
{
    public Table<Order> Orders;
    public Northwind(string connectionInfo):base(connectionInfo)
    {
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

无熵~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值