Search code examples
c#sql-serverconfigurationdata-access-layerlinq2db

linq2db exception: "Configuration string is not provided". I don't have a web/app.config, but even if I give the string explicitly, same exception


I'm working on a training project developing a DAL for Northwind with Entity Framework and another DAL with linq2db in the same project.

I keep getting the error when I run a test which uses linq2db:

LinqToDB.LinqToDBException : Configuration string is not provided.

I guess it's because I didn't follow the step 3 of the template "CopyMe.SqlServer.tt.txt", which says to add this to the web/app.config.file:

<connectionStrings>
    <add name="Northwind" providerName="System.Data.SqlClient"
        connectionString="Data Source=(local);Initial Catalog=Northwind;Integrated Security=true" />
</connectionStrings>

Because there's no such file in my project.

When I try passing the configuration like this, it doesn't work either, same exception:

using var db = new NorthwindDB(Resources.ConnectionString);
var q = db.Customers.Select(c => c);

foreach (var c in q)
    Console.WriteLine(c.ContactName);

What should I do? What am I missing?

upd: Sorry for misinformation. When I pass the configuration explicitly, the exception is:

Configuration 'Data Source=(local);Initial Catalog=Northwind;Integrated Security=true' is not defined.


Solution

  • Thanks to @AlwaysLearning.

    This method from linq2db github was a solution in my case: https://github.com/linq2db/linq2db#using-connection-string-settings-provider

    public class ConnectionStringSettings : IConnectionStringSettings
    {
        public string ConnectionString { get; set; }
        public string Name             { get; set; }
        public string ProviderName     { get; set; }
        public bool   IsGlobal         => false;
    }
    
    public class MySettings : ILinqToDBSettings
    {
        public IEnumerable<IDataProviderSettings> DataProviders
            => Enumerable.Empty<IDataProviderSettings>();
    
        public string DefaultConfiguration => "SqlServer";
        public string DefaultDataProvider  => "SqlServer";
    
        public IEnumerable<IConnectionStringSettings> ConnectionStrings
        {
            get
            {
                yield return
                    new ConnectionStringSettings
                    {
                        Name             = "Northwind",
                        ProviderName     = ProviderName.SqlServer,
                        ConnectionString =
                            @"Server=.\;Database=Northwind;Trusted_Connection=True;Enlist=False;"
                    };
            }
        }
    }
    

    Then put this somewhere at the app start:

    DataConnection.DefaultSettings = new MySettings();