Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

umbraco 7 how to access database MVC

I have Umbraco 7 website with MVC.

I want to perform some custom action on the database.

As I understand I should be using DbContext to connect.

I have referenced System.Data.Entity to get to DbContext class. However when I'm trying to use DbContext I'm getting an error saying

The type or namespace name 'DbContext' could not be found (are you missing
a using directive or an assembly reference?)

In my models namespace:

public class umbracoDbDSN : DbContext
{
    //some code
}

Can you let me know what I am missing?

Thanks

like image 591
nickornotto Avatar asked Dec 19 '22 13:12

nickornotto


1 Answers

You are mixing things up. Umbraco uses PetaPoco as ORM, not entity framework. You don't need to include the System.Data.Entity. Neither you need the DbContext.
However, if you have existing DataLayer logic which you need to incorporate, for legacy systems, you might need to continue with your code above. Then look for entity framework tutorials on the internet to continue your journey.

If you are not dragging legacy stuff, then the question is: do you want to perform queries on custom tables or do you want to query the Umbraco tables for some reason.

Let's start with the last one. Querying the umbraco tables: If you want to connect to the umbraco SQL tables, I start wondering why. There is a ContentCache, which is blasting fast, and it enables you to query very quickly everything you need from the content section. You have API's for relationships, media, users, members and everything you need. So the question remains, WHY would you ever connect to the umbraco tables.

However, if you want to store data in custom tables, I would read this article of Warren: http://creativewebspecialist.co.uk/2013/07/16/umbraco-petapoco-to-store-blog-comments/

The idea is simple, you reuse the existing code base to extend umbraco behaviour without storing stuff in the content section.

Below a simple example for reusing the databaseconnection while querying some proper created table...

var db = ApplicationContext.Current.DatabaseContext.Database;
// Fetch a collection of contacts from the db.
var listOfContacs = db.Fetch<Contact>(new Sql().Select("*").From("myContactsTable"));
like image 58
dampee Avatar answered Jan 03 '23 00:01

dampee