SQLite as in-memory database for SQL Server - c#

My setup is similar to this for testing dapper calls for SQL Server using in-memory SQLite (http://mikhail.io/2016/02/unit-testing-dapper-repositories/) using this lib: https://github.com/ServiceStack/ServiceStack.OrmLite
I'm using dapper with ad hoc SQL for my DAL and wanted to test data access layer without dependency on SQL Server. I used SQLite in-memory database. Problem is SQL syntax are different between SQL Server and SQLite.
For example I have a query that returns paged results using offset and fetch next, but SQLite only supports limit and offset.
What if any suggestions you have for me to do my in memory unit test? I didn't go the EF route with mocked db context as dapper is more performant and didn't want to use stored procedures as I wanted to test my SQL as well. I'm not looking to mock my database calls.

Ormlite's Typed API is RDBMS agnostic so as long as you stick to OrmLite's Typed API you will be easily able to alternate between different databases by just changing the connection string and dialect provider, e.g:
//SQL Server
var dbFactory = new OrmLiteConnectionFactory(connectionString,
SqlServerDialect.Provider);
//InMemory Sqlite DB
var dbFactory = new OrmLiteConnectionFactory(":memory:",
SqliteDialect.Provider);
Then you can use either database to create, persist and query POCO's, e.g:
using (var db = dbFactory.Open())
{
db.DropAndCreateTable<Poco>();
db.Insert(new Poco { Name = name });
var results = db.Select<Poco>(x => x.Name == name);
results.PrintDump();
}
But if use the Custom SQL API's to execute MSSQL-specific SQL you wont be able to execute that against SQLite. You can make use of the mockable support in OrmLite, but I'd personally recommend sticking to OrmLite's RDBMS agnostic typed API's instead.

Related

Programmatically script or migrate SQL Compact database for importing into SQL Server

I have used ErikEJ's SQLite/SQL server Compact Toolbox which allows migration from a compact database to SQL Server, but I am trying to implement this process into my ASP.NET application.
The user will have an already completed SQL Server Compact database.
The process will be
1) User selects the database
2) Existing SQL Server database will be deleted
3) Compact database will be scripted/migrated into SQL Server
The part I am unsure of is how I should script or migrate the SQL Compact database. Deleting and creating a new database on the server itself seems easy enough. I have been digging around in the System.Data.SqlServerCe class for a while and am unsure what the best approach would be.
Using my scripting API, you can do something like this:
using (IRepository ceRepository = new DB4Repository(#"Data Source=C:\Data\SQLCE\Test\nw40.sdf"))
{
string fileName = Path.GetTempFileName();
var generator = new Generator4(ceRepository, fileName);
generator.ScriptDatabaseToFile(Scope.SchemaData);
using (IRepository serverRepository = new ServerDBRepository4("Data Source=.;Trusted_Connection=true;Initial Catalog=Test"))
{
serverRepository.ExecuteSqlFile(fileName);
}
}
See my blog post here: http://erikej.blogspot.dk/2013/03/sql-server-compact-code-snippet-of-week_8.html
A more complete implementation (from my Toolbox)
https://github.com/ErikEJ/SqlCeToolbox/blob/master/src/GUI/SqlCe35Toolbox/Commands/SqlServerDatabaseMenuCommandsHandler.cs#L370

Is there any way to create a DbCompiledModel without having EF load provider information from the database?

I'd like to construct an EF DbCompiledModel from a DbModelBuilder without actually connecting to a database. Is there any way to do this? It looks like I can build a model using a DbProviderInfo, but I don't know how to get a providerInvariantName & providerManifestToken.
The reason I would like to do this is that I want to leverage the EF to SQL compiler offline to generate some queries without having access to the database. I'm using EF 5.
For SqlServer the provider invariant name is "System.Data.SqlClient" and the provider manifest tokens are "2005" for SqlServer 2005, "2008" for SqlServer 2008. In EF6 there are also "2012" for SqlServer 2012 and "2012.Azure" for Azure.

WCF and MVC : Call stored procedures from web mvc application

I've done a wcf service that deals with a database. In that WCF service i've created some stored procedures. That service is now accessible from my network (http: //myIP/MysService.csv/) and my stored procedures are accessible that way : http: //myIP/MysService.csv/MyProcedure?myParam=XXX.
I've a MVC4 application that is working with some local data (by local I mean a local database and a local WCF service, called that way for requests by example :
public int getClientID(string login)
{
var context = new MyLocalService.MyLocalEntityEntities(new Uri(http://localhost:12345/MyWCF.svc/));
var persons = context.PERSON.ToList();
var cli = from person in persons
where person.LOGIN == login
select person.CLIENT_ID;
int cliID = (int) cli.First();
return cliID;
}
Now, I'd like to plug the 2 : delete all the part that works with local data (var context=...) and replace it by a call to the stored procedure of my WCF service. How to do it ?
I've try to add my service using right click-> add as a service reference -> http: //myIP/MysService.csv/ for address by I cannot access to stored procedures. Is it the right way to work and if not, how to do it ? Thanks !
If you're going to use Stored Procedures then look at the SqlCommand class that will allow you to execute stored procedures on the database.
The other idea would be to consider what kind of Object-Relational Mapping tool you are using that may allow for SQL commands to be executed directly since you already seem to be using some LINQ in your code.
You'd pair the SqlCommand class with a SqlConnection class that have a direct connection to the database, presuming the stored procedure is MS-SQL Server or SQL Express where you want to execute the procedure in the DB. Unless you have a very different configuration than what I've seen, most calls to stored procedures are done by wrapping some using statements for the connection and command to run the procedure. Calling stored procedure from C# code has an example if you need it.

How to know the state of an sql instance in a c# program

I have one database with one mirror in high-safety mode (using a witness server at the moment but planing to take him out), this database will be used to store data gathered by a c# program.
I want to know how can I check in my program the state of all the SQL instances and to cause/force a manual failover.
is there any c# API to help me with this?
info: im using sql server 2008
edit: I know I can query sys.database_mirroring but for this I need the principal database up and runing, I would like to contact each sql instance and check their status.
Use SQL Server Management Objects (SMO).
SQL Server Management Objects (SMO) is a collection of objects that are designed for programming all aspects of managing Microsoft SQL Server. SQL Server Replication Management Objects (RMO) is a collection of objects that encapsulates SQL Server replication management.
I have used SMO in managed applications before - works a treat.
To find out the state of an instance, use the Server object - is has a State and a Status properties.
after playing around a bit I found this solution (i'm not if this is a proper solution, so leave comments plz)
using Microsoft.SqlServer.Management.Smo.Wmi;
ManagedComputer mc = new ManagedComputer("localhost");
foreach (Service svc in mc.Services) {
if (svc.Name == "MSSQL$SQLEXPRESS"){
textSTW.Text = svc.ServiceState.ToString();
}
if (svc.Name == "MSSQL$TESTSERVER"){
textST1.Text = svc.ServiceState.ToString();
}
if (svc.Name == "MSSQL$TESTSERVER3") {
textST2.Text = svc.ServiceState.ToString();
}
}
this way i'm just looking for the state of the services (Running/Stoped) and is much faster, am I missing something?

Linq to Entities: see the resulting query (context.Log = Console.Out)

I just realized if your C# application use LINQ-TO-SQL classes to interface with the database, you can your query like this
using (DatabaseContext context = new DatabaseContext())
{
context.Log = Console.Out;
var query = from Person p in context.People
where person.Name == "john"
select p;
Console.WriteLine(query.Name);
}
What is the equivalent in LINQ-TO-ENTITY (is this another name for ADO.NET?) for
context.Log = Console.Out
Or there is another way to see your actual SQL query to the database?
I always use SQL Profiler if you have MS SQL Server. What DBMS is this for? LINQ 2 Entities supports multiple DB types.
This also works...
var cust = (from c in context.Customers select c);
string sql = ((ObjectQuery)cust).ToTraceString();
From MSDN forums
Using EntityFrame 6 it is possible to just to a ToString() on your query at least when using MySQL
var cust = (from c in context.Customers select c);
string sql = cust.ToString();
As Greg in the comments notes, this gives you the parameterized query, so you will need to add in the values you want to use.
You can trace your SQL when using Linq2Entities
https://stackoverflow.com/questions/137712/sql-tracing-linq-to-entities
You may also want to look at this tool
Huagati Query Profiler
I believe the Tabular Data Stream (TDS) protocol used by Microsoft SQL Server sends commands and responses in plain text by default so unless you encrypt the connection between your SQL Server and the client, you should be able to view both the request and response with a comprehensive packet sniffer.
It will take some work but using a packet sniffer in this manner should allow you to see what T-SQL your LINQ is getting translated to.
Side Notes:
I recommend that you encrypt all communications between your client and SQL server unless both the client and server reside on the same machine and you are doing development testing.
If you can't risk using a decyrpted connection for testing purposes, your packet sniffer may have a plugin that will allow you to decrypt encrypted traffic, but I am not sure if there are any risks in using such a decryption plugin.
EF doesn't have a direct parallel to the stream based loging that LINQ to SQL uses. There are a number of profiling options available for a variety of costs. I've discussed some of these options at http://www.thinqlinq.com/Post.aspx/Title/LINQ-to-Database-Performance-hints. You can find a listing of these profilers and other LINQ tools at http://www.thinqlinq.com/Post.aspx/Title/linq-tools.

Categories