C#中的LINQ to SQL连接字符串(新手) [英] C# Linq to SQL connection string (newbie)
问题描述
我是一个新的LINQ to SQL的学习,这是我的第一个创建一个数据浏览器程序的尝试。这个想法很简单,我想创建一个软件,它能够在数据库中查看表的内容。这就是它。
i am a new linq to sql learner and this is my very first attempt to create a data viewer program. The idea is simple, i'd like to create a software that is able to view content of a table in a database. That's it.
我有一个早期的问题已经在这里,我已经看过很多tutes和网上的文章,但我仍然无法修复的bug。
I got an early problem here already and i have seen many tutes and articles online but I still cant fix the bug.
下面是我的代码:
static void Main(string[] args)
{
string cs = "Data Source=localhost;Initial Catalog=somedb;Integrated Security=SSPI;";
var db = new DataClasses1DataContext(cs);
db.Connection.Open();
foreach (var b in db.Mapping.GetTables())
Console.WriteLine(b.TableName);
Console.ReadKey(true);
}
当我试图检查 db.connection.equals (NULL);
返回假
,所以我想我已经成功地连接到数据库,因为没有错误可言。但上面的代码不会打印出任何内容到屏幕上。
When I tried to check db.connection.equals(null);
it returns false
, so i thought i have connected successfully to the database since there is no error at all. But the code above doesn't print anything out to the screen.
我有点迷路了,不知道是怎么回事。 ?有谁知道是怎么回事错在这里。
I kind of lost and don't know what's going on here. Does anyone know what is going wrong here?
推荐答案
好吧,让我们来看看其中的一些行:
Ok, let's look at some of these lines:
var db = new DataClasses1DataContext(cs);
这是一个构造一个完全正常的和精细的呼叫。由于DataContext的实现IDisposable,当你使用它的实际,考虑使用using语句。
This is a perfectly normal and fine call to a constructor. Since DataContext implements IDisposable, when you are using it for real, consider using the using statement.
using (var db = new DataClasses1DataContext(cs))
{
// do stuff with db here
} // when leaving the block, db is disposed - even in the case of an exception.
db.Connection.Open();
不要这样做。 DataContext的打开和关闭连接时,它需要。
Don't do this. DataContext will open and close the connection when it needs to.
foreach (var b in db.Mapping.GetTables())
Console.WriteLine(b.TableName);
嗯,也许是在映射没有桌子。你是从服务器资源管理器拖放表到设计表面?
Hmm, maybe there are no tables in the mapping. Did you drag a table onto the designer surface from the server explorer?
大多数人会质疑,而不是细读的映射表。考虑下面的代码,而不是:
Most people would query a table instead of perusing the mappings. Consider this code instead:
foreach (var customer in db.Customer.Take(10))
{
Console.WriteLine(customer.Name);
}
下面是展示如何视频
Here's a video showing how to drag a table onto the designer surface from the server explorer:
的 http://www.youtube.com/watch?v=z9L11qrw9gk
这篇关于C#中的LINQ to SQL连接字符串(新手)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!