开发者

How can I create Linq To SQL Classes with the VS designer when using a Connection String

As you may have seen from my previous posts开发者_高级运维 I'm starting to teach myself MVC and C# as it's time for me to move from being a designer to a developer. I've been told not to use the Server Explorer in Visual Studio but just connect to my database with a connection string in the web.config. I've done this but obviously the LINQ to SQL Designer in Visual Studio doesn't seem to know or recognise my database connection and I can't just drag onto the designer to make the classes. Must I create these manually or am I missing something?

Any ideas are appreicated.

Cheers

Mark


The DataContext class has a constructor that takes a connection string parameter.


I think I've sorted this by changing the connection settings within the designer properties


You can generate your classes using Server Explorer and just populate the server, database, authentication fields in there with the details from your connection string.

Then, as shadowfoxmi states, when you instantiate your DataContext class, use the constructor that takes a connection string or a pre-set up SqlConnection instance.

Personally I prefer to have a static class containing a single static method GetDataContext() which returns a DataContext instance already set up with the correct connection string, timeouts etc. Then I ensure that no code instantiates a DataContext manually, but rather all instances come from that static method. You can make this method as complex as you need, e.g. you might have the code instantiate DataContexts with different connection strings depending on the deployment environment (e.g. staging, production, local dev) etc.

In deployment, depending on your needs, it may be a good idea to make sure that the details that Server Explorer will put into your app.config / web.config file are removed.


I always create a wrapper that does something like:

public static class DBCreator
{
   public static MyDataContext Create()
   {
       return new MyDataContext(ConfigurationManager.ConnectionStrings["ConnName"].ConnectionString);
    }
}

And then use this everywhere. You can also add overloads to accept a DataLoadOptions or whatever else you want to pass in.

HTH.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜