Geeks With Blogs
Fran Hoey

I'm just getting to grips with MVC linq etc etc and came across what looks like a common stumbling block. For the more experienced of you reading this please refrain from shouting "Dumbass" at me.

All the tutorials are either Code First examples or they create the database from scratch in the App_Data directory. All well and good for a tutorial that need to be easily portable to the readers computer, but not very helpful when setting up a full scale MVC application.

My first problem was my lack of knowledge of Linq to SQL. If you fall into this category have a look at this link - it's gold dust.

http://weblogs.asp.net/scottgu/archive/2007/05/19/using-linq-to-sql-part-1.aspx

Finally, how to add an external SQL database to your MVC project:

  1. Right click on "Models" folder, select "Add New Item"
  2. Add a "Link to SQL Classes" item
  3. Open your "Server Explorer" pane (if you cant see it try "View" on the menu bar and "Server Explorer"
  4. Right click on "Data Connections" and select "Add Connection"
  5. Follow the instructions.
  6. Almost there....
  7. Expand your newly added database to view the tables.
  8. Drag the tables you want over to the main pane of the "Link to SQL Classes" item you added at the start.
  9. Hey presto, you have a database context you can run Linq queries against.

Please bear in mind you will need to use the "Models" namespace to reference you database context objects.

....

And now back to highly sophisticated programming!

Posted on Tuesday, March 29, 2011 10:14 PM ASP.NET , MVC | Back to top


Comments on this post: Connecting an MVC project to an SQL database

# re: Connecting an MVC project to an SQL database
Requesting Gravatar...
dumbass ;-)

I'd suggest not using Linq to SQL for a "full scale" website, and use either Entity Framework, or NHibernate 3.

Entity Framework is much closer to the stuff you have been doing with Linq to SQL. I personally prefer NHibernate as I find it more flexible and using it with something like fluentNhibernate makes it pretty simple.

From there you may pretty quickly want to learn the "Repository" pattern.

Which may all seem a bit daunting at first, but its well worth getting to grips with.


Left by Keith Nicholas on Mar 30, 2011 12:44 AM

# re: Connecting an MVC project to an SQL database
Requesting Gravatar...
Thank you, that's set my reading for the day.

I've been developing in .net for nearly 10 years, but MVC is new to me. I'm like a kid in a sweet shop.
Left by Fran Hoey on Mar 30, 2011 10:17 AM

# re: Connecting an MVC project to an SQL database
Requesting Gravatar...

The information is nicely presented in post, I am happy to find many useful facts. Thanks for sharing

prestiti veloci
Left by nehree on Aug 11, 2011 2:10 AM

Comments have been closed on this topic.
Copyright © FranHoey | Powered by: GeeksWithBlogs.net