Linq to SQL DataContext:如何加载数据? [英] Linq to SQL DataContext: how to load data?

查看:68
本文介绍了Linq to SQL DataContext:如何加载数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(我对Linq to SQL完全陌生)我正在创建一个与数据库紧密合作的Web应用程序,我正在寻找最快,连接时间效率最高的模型,并相信Linq to SQL就是这样.我正在使用C#/.Net4/Visual Studio 2010

(I'm completely new to Linq to SQL) I am creating a web app that works very closely with a database, I'm looking for the quickest and connection time efficient model and believing Linq to SQL to be this. I'm using C#/.Net4/Visual Studio 2010

为简单起见,我有一个Web .aspx页面,其中包含许多asp文本框.我想通过Linq将它们的Text值从SQL数据提供给SQL对象.我还有一个名为DataClasses.dbml的文件,在设计视图中添加了一个表.到目前为止,我在网页中隐藏的代码是:

For simplicity sake, I have a web .aspx page containing a number of asp Text Boxes. I want to give their Text values from SQL data via Linq to SQL object. I also have a file called DataClasses.dbml with a a table added in the design view. The code I have so far in my web page code-behind is:

DataClassesDataContext db = new DataClassesDataContext(getConnectionString);

var table = from t in db.MyTable
            where t.PK == 2
            select new { t.col1, t.col2, t.col3};

db.Connection.Open();
db.  // What's the best way of loading the object?
db.Connection.Close();

然后如何访问列值?还是我将其数据绑定到数据表?如果可以,怎么办?

How do I then access the column values? Or do I databind it to a datatable? If so, how?

myTextBox1.Text = table.???col1.value;

推荐答案

您无需打开或关闭连接. LinqToSql为您抽象化了这一点.

You don't need to open or close the connection. LinqToSql abstracts that away for you.

创建查询后,您可以执行查询并使用SingleOrDefault()将行作为对象检索.

Once you created the query, you can execute it and retrieve the row as an object using SingleOrDefault().

using (var db = new DataClassesDataContext(getConnectionString))
{
    var query = from t in db.MyTable
                where t.PK == 2
                select new { t.col1, t.col2, t.col3};
    var myObject = query.SingleOrDefault();
}

您还可以使用lambda表示法简化此操作:

You can also simplify this operation by using the lambda notation:

using (var db = new DataClassesDataContext(getConnectionString))
{
    var myObject = db.MyTable.SingleOrDefault(t => t.PK == 2 )
}

要访问对象,您可以直接访问列,因为它们已映射到相应的属性:

To access the object you can directly access the columns since they have been mapped to the corresponding properties:

myTextBox1.Text = myObject.col1;

这篇关于Linq to SQL DataContext:如何加载数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆