The Author Online Book Forums are Moving

The Author Online Book Forums will soon redirect to Manning's liveBook and liveVideo. All book forum content will migrate to liveBook's discussion forum and all video forum content will migrate to liveVideo. Log in to liveBook or liveVideo with your Manning credentials to join the discussion!

Thank you for your engagement in the AoF over the years! We look forward to offering you a more enhanced forum experience.

elcapitankyle (1) [Avatar] Offline
#1
Hi. I'm trying to work through the sample programs in the book and ran into this error when trying to connect to the NORTHWND.mdf db:

System.Data.SqlClient.SqlException was unhandled
Message="A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)"

I'm pretty sure that means it can't open the database however I'm not sure what exactly I've done wrong. Any suggestions to get me jump started here?

This is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Text;

namespace HelloLinqToSql
{
class HelloLinqToSql
{
[Table(Name = "Contacts")]
class Contact
{
[Column(IsPrimaryKey=true)]
public int ContactID {get; set;}
[Column(Name="ContactName")]
public string Name {get; set;}
[Column]
public string City {get; set;}
}

static void Main(string[] args)
{
string cxn = @"C:workProjectsLinqInActionDataNORTHWND.mdf";
DataContext db = new DataContext(cxn);

var contacts =
from contact in db.GetTable<Contact>()
where contact.City == "Paris"
select contact;

foreach (var contact in contacts)
{
Console.WriteLine("Hello " + contact.Name);
}
}
}
}
jwooley (123) [Avatar] Offline
#2
Re: Connection error when running HelloLinqToSql
Your connection string appears to be invalid. It needs to be more than just the file path. Compare your string with the ones in the config files in the samples. Assuming your northwind table is in the directory you mentioned, see if the following string helps:

"Data Source=.SQLEXPRESS;AttachDbFilename=C:workProjectsLinqInActionDataNORTHWND.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"

Jim Wooley
fabrice.marguerie (224) [Avatar] Offline
#3
Re: Connection error when running HelloLinqToSql
The connection string with just the file path is valid. This is what is used in the HelloLinqToSql sample. However, it seems that it doesn't work on all machines. It may depends on the version of SQL Server that is installed, on the name of the server instance, and on whether user instances are allowed.

A connection string like the one Jim gives is more likely to work on all machines, provided that the Data Source and AttachDbFilename values are customized.

Fabrice