C# Linq to SQL connection string (newbie)

只谈情不闲聊 提交于 2019-12-06 06:59:40

Ok, let's look at some of these lines:


var db = new DataClasses1DataContext(cs);

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();

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

Try change your connection string to below

string cs = @"Data Source=.\;Initial Catalog=somedb;Integrated Security=SSPI;";
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!