Dalupus
Dalupus

Reputation: 1120

Trying to connect to simple mdf file

I am trying to work through Essential Linq and am having an issue simply connecting to the supplied .mdf file.

I have saved off the file at C:\DATA\NORTHWND.MDF. I am using Visual Studio 2013

The code looks like the following:

using System;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Linq;
using System.IO;

namespace LinqToSqlWithoutDesigner
{
    [Table(Name="Customers")]
    class Customer
    {
        [Column]
        public string CustomerID;
        [Column]
        public string City;
    }

    class Program
    {
        static void Main(string[] args)
        {
            DataContext db = new DataContext(@"C:\DATA\NORTHWND.MDF");

            var query = from c in db.GetTable<Customer>()
                    where c.City == "London"
                    select new { CustId = c.CustomerID, City = c.City };

            foreach(var cust in query)
            {
                Console.WriteLine(cust);
            }
        }
    }
}

I also tried to use:

string connectionString = @"Data Source=.\SQLEXPRESS;
                      AttachDbFilename=c:\data\northwind.mdf;
                      Integrated Security=True;
                      Connect Timeout=30;
                      User Instance=True";
DataContext db = new DataContext(connectionString); 

But I always get the error :

Unhandled Exception: System.Data.SqlClient.SqlException: 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)

Upvotes: 0

Views: 4689

Answers (3)

swe
swe

Reputation: 1455

Looks like you do not have SQL Server Express on your computer or the requested network interface protocol is not activated.

For a .mdf file you NEED to have an up and running SQL Server

Upvotes: 3

Dalupus
Dalupus

Reputation: 1120

Ok so here was the string which allowed me to connect to the MDF file

DataContext db = new DataContext(@"Data Source=(localdb)\v11.0;
                                   Integrated Security=true;
                                   AttachDbFileName=C:\DATA\NORTHWND.MDF");

More information about LocalDB can be found at: http://blogs.msdn.com/b/sqlexpress/archive/2011/07/12/introducing-localdb-a-better-sql-express.aspx

Upvotes: 1

Med.Amine.Touil
Med.Amine.Touil

Reputation: 1235

the catalog name does not exist in your connection string

add to connectionString:

catalog=yourDbName

NB: You can not connect directly to an MDF file.

If the database does not exist in your database server you need to use the .mdf file and the .ldf file.

Then use your connection string and add the catalog name as i mentioned

Upvotes: 0

Related Questions