C# orm linq 真的不错

也是C# 一大进步,让C#摆脱了传统开发模式,个人还是比较喜欢的。跟java中的hibernate有点像,并且符合C# 开发人员的习惯,个人感觉。

一下内容并非原创,转载msnd(http://msdn.microsoft.com/zh-cn/library/bb882643.aspx),

介绍了 linq 对数据库进行增删改查,有兴趣的可以看看。

 

.NET Framework 4
    Visual Studio 2008
此内容为质量更高的人工翻译。若想同时查看此页面和原始英文页面的内容,请单击“首选项”然后选择“经典视图”作为您的查看首选项。

您可以查询表中的信息、在表中插入信息以及更新和删除表中的信息。

选择

LINQ to SQL

在下面的示例中,检索来自伦敦的客户的公司名称并将其显示在控制台窗口中。

// Northwnd inherits from System.Data.Linq.DataContext.
Northwnd nw = new Northwnd(@"northwnd.mdf");
// or, if you are not using SQL Server Express
// Northwnd nw = new Northwnd("Database=Northwind;Server=server_name;Integrated Security=SSPI");

var companyNameQuery =
    from cust in nw.Customers
    where cust.City == "London"
    select cust.CompanyName;

foreach (var customer in companyNameQuery)
{
    Console.WriteLine(customer);
}


插入

SubmitChanges 即可。

Customers 表添加了一位新客户以及有关该客户的信息。

// Northwnd inherits from System.Data.Linq.DataContext.
Northwnd nw = new Northwnd(@"northwnd.mdf");

Customer cust = new Customer();
cust.CompanyName = "SomeCompany";
cust.City = "London";
cust.CustomerID = "98128";
cust.PostalCode = "55555";
cust.Phone = "555-555-5555";
nw.Customers.InsertOnSubmit(cust);

// At this point, the new Customer object is added in the object model.
// In LINQ to SQL, the change is not sent to the database until
// SubmitChanges is called.
nw.SubmitChanges();


更新

SubmitChanges 以更新数据库。

SubmitChanges 以将所做的更改发送至数据库。

Northwnd nw = new Northwnd(@"northwnd.mdf");

var cityNameQuery =
    from cust in nw.Customers
    where cust.City.Contains("London")
    select cust;

foreach (var customer in cityNameQuery)
{
    if (customer.City == "London")
    {
        customer.City = "London - Metro";
    }
}
nw.SubmitChanges();


删除

SubmitChanges 以提交所做的更改。

说明

如何:从数据库中删除行 (LINQ to SQL)

SubmitChanges 以将删除内容转发至数据库。

Northwnd nw = new Northwnd(@"northwnd.mdf");
var deleteIndivCust =
    from cust in nw.Customers
    where cust.CustomerID == "98128"
    select cust;

if (deleteIndivCust.Count() > 0)
{
    nw.Customers.DeleteOnSubmit(deleteIndivCust.First());
    nw.SubmitChanges();
}

相关文章:

  • 2021-11-03
  • 2022-12-23
  • 2022-12-23
  • 2021-12-05
  • 2021-10-31
  • 2022-02-08
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-01-11
  • 2022-02-13
  • 2022-12-23
  • 2021-07-25
  • 2021-07-06
  • 2021-12-29
  • 2022-12-23
相关资源
相似解决方案