Saturday, October 6, 2012

[SQL/MySQL/.NET] Setting databases for .NET usage

After setting up WCF services and having my android devices consuming it, I wanted my WCF to be the layer that communicates to a database resource. At first, I had a hard time with getting started with SQL Server, so I went with MySQL instead.

NOTE: In your IIS, make sure the ASP.NET 4.0 Application Pool "Identity" is set to Local System. This is the reason why SQL Server wouldn't go so smooth at first, but I will discuss details later.

MySQL setup:

1. Download MySQL server installer, MySQL OBDC connector, and MySQL Net connector. Optionally, download the Workbench, which provides a GUI solution for handling SQL functions. If you're lame like me, you would use this tool.

2. Set up your tables using Workbench or commandline.

3. In Visual Studio, add a new ADO.NET Entity Data Model and point to your MySQL Server when prompted. If you don't know the server name or IP Addy, you can always go to the Workbench and see the properties there. Mine was 127.0.0.1. Follow through with creating the .edmx file.

4. Now you should see the newly created entities right in front of you. The name of the object is exactly what the header of the entity is. So you can instantiate it like:

User objUser = new User();

Of course, we don't want to instantiate like this, but rather grab the info from the database and create the object then. We will use LINQ to do so.

 Now look for Entity Container Name in the properties of your .edmx file. This is the object you use to connect to the database. So lets just put 2 and 2 together with the entity object included:

MyDBEntities db = new MyDBEntities();
List<User> users = ( from p in db.Users select p ).ToList();

This should select all users from a "Users" table and return it as a list of User objects.

Run the WCF Test Client and test if it works.

SQL Server setup:

Okay, if you installed SQL Server 2008, I believe that it should've created an instance of SQLEXPRESS. So we will just go with this default setup, although, you might have set up another instance, you'll just have to remember the server name for that one.

So by default, your instance of SQLEXPRESS should be your <computername>\SQLEXPRESS. (ex. KETTLEPOT-PC\SQLEXPRESS).

Create tables in SQL Management Studio (Free) by using the server name.

From now on, follow step 3 from the MySQL setup section to configure everything in VS2010.

 Now, if you're getting the "underlying provider" error when you run the WCF Test Client and invoke your method, check out the "NOTE" at the beginning of this post.

Hope that helps!!!!


No comments:

Post a Comment