
Using LINQ to SQL with Access
433
Source
— The name of the field in the database (probably the same as the property’s name in
the class)
Type
— The property’s type in the class (for example, string)
After you build the model, Visual Studio generates the classes you need. Now you just need to add
code to use them.
If you are using a Microsoft Access database, start by adding the following line at the top of the file.
The connection object that you need to open the database is defined in this namespace. (For other
kinds of databases, you may need to use different database objects in other namespaces.)
using System.Data.OleDb;
Next build a database connection. The LinqToSqlAccess example program that is available in this
lesson’s download uses the following code to build its connection:
// Get the database’s location.
string filename = Path.GetFullPath(
Application.StartupPath + @“\..\..\CustomerData.mdb”);
// Connect to the database.
using (OleDbConnection conn = new OleDbConnection(
“Provider=Microsoft.Jet.OLEDB.4.0;” +
“Data Source=” + filename))
{
This program assumes the CustomerData.mdb database is located two directory levels above where
the program is executing. This is true if the program is running from its
bin\Debug directory.
The program gets the location of the database file. It creates a new
OleDbConnection object, passing
its constructor a connect string that includes the location ...