1

To learn ServiceStack, I'm developing an API based in Northwind database (a SQL Server CE sdf file). My solution has 3 projects:

  • Northwind.Data. Database and POCO classes
  • Northwind.ServiceModel. DTO classes
  • Northwind.ServiceInstance. Service classes

What's the best way to access data? Currently the database is in Northwind.Data /App_Data folder. Can I access database path from Web.config and read it in AppHost class to create IDbConnection factory?

Thanks in advance.

Merrin
  • 514
  • 7
  • 20

1 Answers1

1

What's the best way to access data?
I don't think OrmLite has support for SQL Server CE but there is this. Best way might be to just use SqlCeConnection within your Services.

Can I access database path from Web.config and read it in AppHost class to create IDbConnection factory?
You should be able to add the connection string to the Web.config file.

<add name="Test" connectionString="Data Source=C:\Northwind.sdf" />  

If I'm correct about OrmLite not supporting SQL CE and you want IDbConnectionFactory like syntax in your Services you could look into using DBProviderFactories.

The simplest (not the best) thing I can think of would be doing something like below.

Create a 'bare bones' factory for SqlCEConnection. This assumes you have the connection string in your Web.config file

public class SqlCeFactory
{
    public SqlCeConnection OpenConnection()
    {
        var conn = new SqlCeConnection(ConfigurationManager.ConnectionStrings["Test"].ToString());
        try
        {
            conn.Open();
            return conn;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}

Register it the SqlLCeFactory in your AppHost

public override void Configure(Funq.Container container)
{
    container.Register<SqlCeFactory>(new SqlCeFactory());
}

Inject it into your Service(s)

public class SourceService : ServiceStack.ServiceInterface.Service
{
    public SqlCeFactory DbFactory { get; set; }

    public object Get(SomeRequest request)
    {
        using (var con = DbFactory.OpenConnection())
        {
            //use SqlCeConnection()
        }

        //more code
    }
}
paaschpa
  • 4,816
  • 11
  • 15
  • 1
    Remove this: `catch (Exception ex) throw ex;` That will discard the stack trace. See [Exceptions Best Practices](http://stackoverflow.com/questions/22623/). – Dour High Arch Apr 17 '13 at 18:08
  • Thanks for replies. @paaschpa currently my sdf file is in Northwind.Data/App_Data folder (in the project Northwind.Data). What I want to do is access (ConnectionString in web.config) from Northwind.ServiceInstance project (AppHost.Configure method). – Merrin Apr 18 '13 at 07:52