Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use LINQ2SQL with ODBC?

I am writing and ASP.NET MVC application with SQL Server 2008. Unfortunately, the only way I can connect to that database is through a dsn or ODBC in my production environment. In development I have used a Linq2SQL layer to access data in the database. Is there a way that I can force Linq2SQL to use ODBC for connectivity rather than a SQL Client connection?

like image 351
Tassadaque Avatar asked Jan 10 '11 04:01

Tassadaque


People also ask

Is ODBC faster than OLE DB?

2- OLE DB is more faster than ODBC ... Microsoft ADO, OL DB, and ODBC MDAC Components. Developers can use any of MDAC's components (ODBC, OLE DB, and ADO) to connect to several relational and non-relational data stores.

Should I use ODBC or Oledb?

OLEDB vs ODBC Platform SupportOLEDB is a Windows-only database API. It uses the Component Object Model (COM), which is unavailable on other platforms. Meanwhile, ODBC is supported on Windows, Linux, Mac, and UNIX. But both support 32-bit and 64-bit architectures.


3 Answers

Darin, while you could use the solution suggested by Peder, it would defeat the purpose of Linq, as you would be querying the server directly instead of mapping. Tom is right about the "hard coded" but there is a way around, you could create your own interface, a great explanation on the concepts and how to do it is here: http://blogs.msdn.com/b/mattwar/archive/2008/11/18/linq-links.aspx

like image 165
irasnik Avatar answered Nov 08 '22 07:11

irasnik


The code generated by LINQ to SQL has hardcoded references to SQL server connections all over the place, so no. However, you may be able to use DBLinq.

like image 20
Tom Clarkson Avatar answered Nov 08 '22 06:11

Tom Clarkson


Yes, there is a way to use ODBC with LINQ to SQL, but some extra code is required and it will not be nearly as feature-rich. I know that you can get ORM for SELECT statements, but I'm unsure if it will work for UPDATE or DELETE statements.

In the following code snippet, I first defined my model in an empty Linq2Sql .dbml file (I manually created a PurchaseOrder object with the fields that I need). But then note how I'm able to create a new data context by passing in an ODBC connection to it. Finally, there's one last trick: I have to use the data context's ExecuteQuery method along with a SELECT statement to get my purchase orders.

using (var connection = new OdbcConnection("Driver={iSeries Access ODBC Driver};System=serverName;UID=yourUid;PWD=yourPwd"))
{
    var purchaseOrderContext = new Models.PurchaseOrdersDataContext(connection);

    var purchaseOrders = purchaseOrderContext.ExecuteQuery<Models.PurchaseOrder>("SELECT * FROM mySchema.myTable");
}
like image 1
Peder Rice Avatar answered Nov 08 '22 06:11

Peder Rice