15

I'm trying to connect to an on-prem MS SQL database from a universal windows app. I'm making a LOB app using UWP, to support desktop, tablet and mobile use. When trying to connect to a local (intranet) SQL server database, I'm used to using an instance of SqlConnection to connect to a local server, but since SqlConnection is not included in the .NET subset used in UWP, how is this done when using UWP?

I've looked over the official Microsoft samples as well as the how-to guides, and found nothing there about database connection that is not an Azure database. DbConnection seemed like it could be a good way to go, but can't be used since it's abstract, and it's children (for instance Data.SqlClient.SqlConnection) does not seem to be included in the .NET subset for UWP.

Am I missing something super obvious here? As an aside, does anyone know a good namespace reference for UWP?

Edit for non-duplicate: The linked question suggested as a duplicate is for Windows 8/8.1 apps, and while there are some similarities, the code in the accepted answer for that question won't work on UWP. The principle is the same, however, but there should be a better technical reference for Windows 10 apps build with UWP.

3
  • I think you need to consider using web service to make your UWP app and DB connected at least for now. But I think you can keep checking EF 7 which is currently on prerelease version. github.com/aspnet/EntityFramework Oct 1, 2015 at 11:16
  • Thanks for the quick comment! I'm trying to find examples of this but coming up short. Is there any official documentation or any tutorials for this? I haven't used web services before so an answer with a bit more details would get an upvote and accept from me :)
    – Tobbe
    Oct 1, 2015 at 11:24
  • Possible duplicate of How do I interact with SQL in a Windows Store App
    – chue x
    Oct 1, 2015 at 12:38

4 Answers 4

12

With the Windows 10 Fall Creators Update (build 16299) UWP apps can now access SQL Server directly via the standard NET classes (System.Data.SqlClient) - thanks to the newly added support for .NET Standard 2.0 in UWP.

Here is a Northwind UWP demo app: https://github.com/StefanWickDev/IgniteDemos

We have presented this demo at Microsoft Ignite in September 2017, here is the recording of our session (skip to 23:00 for the SQL demo): https://myignite.microsoft.com/sessions/53541

Here is the code to retrieve the products from the Northwind database (see DataHelper.cs in the demo). Note that it is exactly the same code that you would write for a Winforms or WPF app - thanks to the .NET Standard 2.0:

public static ProductList GetProducts(string connectionString)
{
    const string GetProductsQuery = "select ProductID, ProductName, QuantityPerUnit," +
        " UnitPrice, UnitsInStock, Products.CategoryID " +
        " from Products inner join Categories on Products.CategoryID = Categories.CategoryID " +
        " where Discontinued = 0";

    var products = new ProductList();
    try
    {
        using (SqlConnection conn = new SqlConnection(connectionString))
        {
            conn.Open();
            if (conn.State == System.Data.ConnectionState.Open)
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = GetProductsQuery;
                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            var product = new Product();
                            product.ProductID = reader.GetInt32(0);
                            product.ProductName = reader.GetString(1);
                            product.QuantityPerUnit = reader.GetString(2);
                            product.UnitPrice = reader.GetDecimal(3);
                            product.UnitsInStock = reader.GetInt16(4);
                            product.CategoryId = reader.GetInt32(5);
                            products.Add(product);
                        }
                    }
                }
            }
        }
        return products;
    }
    catch (Exception eSql)
    {
        Debug.WriteLine("Exception: " + eSql.Message);
    }
    return null;
}

If you need to support earlier versions than the Fall Creators Update, there is also a way for you to call SqlClient APIs from your UWP app package, via the Desktop Bridge. I have a sample for this published here: https://github.com/Microsoft/DesktopBridgeToUWP-Samples/tree/master/Samples/SQLServer

10
  • 1
    The new support in the Fall Creators Update doesn't require any Desktop Bridge and works on all target devices. Besides, building UWP apps that target only desktop (or target only IoT, etc.) is a completely valid and supported scenario. That's why the platform has the TargetDeviceFamily attribute in the manifest and why we have device-specific extension SDKs (for desktop, IoT, etc.). The developer has the flexibility to decide what they want to target, we don't mandate to target all devices. And frankly, for LOB scenarios most customers are looking to target primarily desktop computers. Oct 8, 2017 at 16:49
  • 1
    Straight from the horse's mouth :) Thanks for the update! Accepting this as correct answer since this seems to be the official way to do it.
    – Tobbe
    Oct 9, 2017 at 6:04
  • 1
    The first link in my answer already points to the code sample for how to connect to SQL Server with .NET Standard 2.0 directly from the UWP app. What is missing? Oct 9, 2017 at 15:11
  • 2
    Added the relevant snippet to the answer. Note that it's the exact same code that one would write for Winforms for the last 15 years - thanks to .NET Standard 2.0. No new concepts to learn for this. Oct 9, 2017 at 16:30
  • 2
    Unfortunately, there is no phone update to 16299 or later, so this feature is not available for Windows 10 Mobile. Dec 2, 2018 at 3:44
4

Here is a simple sample and a video. Not sure if it's enough for you.

Here is a difficult point is

  • how to consume, serialize and deserialize json data. As a .net developer, you can consider using the HttpClient to implement this. And here is another sample and video for your reference. There is another official sample shows how to use Windows.Data.Json namespace.
4
  • This is on the right path, at least. But as I wrote in my edit, most of that code is for 8.1 and won't build for UWP. It's a start, however, and I'll accept it if nothing better comes along in a while.
    – Tobbe
    Oct 1, 2015 at 13:04
  • This got me on the right track, will accept this instead of writing my own answer. Thanks for the effort!
    – Tobbe
    Oct 7, 2015 at 11:00
  • Hi, In the roadmap of Entity Framework 7, it says It would support UWP. And under Database Providers section - says support for SQLServer, SQLLite and InMemory out of the box. So we can expect other providers to support EF7 soon and UWP would have a direct DB connectivity instead of a WebService path. github.com/aspnet/EntityFramework/wiki/Roadmap
    – Venkat
    Nov 4, 2015 at 4:58
  • Entity Framework 7 renamed to Entity Framework Core 1.0
    – Tony
    Feb 4, 2017 at 20:47
2

I am having to go down this same road as well... Looking forward to SQLServer being directly accessible via EF Core directly.

I have watched both tutorials above and since I'm new to developing, it only wet my appetite. I did however find this detailed Video Tutorial on YouTube that walks you thru;

  • creating the WebService
  • creating duplicated POGO classes in WebService and your UWP App
  • creating Web API 2.0 Entity Framework Controllers for each Table you want to create
  • Adding Newtonsoft.JSON and Microsoft.Net.HTTP via NuGet to your UWP App
  • and finally making calls from UWP back to Local SQL Server via Web Service / JSON calls in Code Behind.

Despite this Video NOT being in English, I was able to watch what he was doing then pause and duplicate.

0

Connecting UWP to SQL Server

Note: From windows 10 Fall Creators Update (16299) we can directly access SQL Server database using .NetStanded 2.0

As there is no direct way to connect to SQL Server, we need to create an API for our database in order to connect to SQL Server.

This solution describes

  1. Creating API
  2. Serialize and Deserialize JSON data

1. Creating API

1) Installing ASP.NET and web development

  1. Launch Visual Studio Installer and click Modify enter image description here

  2. Install ASP.NET and web development enter image description here

2) Creating new ASP.NET Web Application (.Net Framework)

  1. Add new project in your solution enter image description here

  2. Select ASP.NET Web Application (.Net Framework) and give a project name enter image description here

  3. Select Web API and click OK enter image description here

3) Connecting to SQL Server database

  1. Add new item in Models folder enter image description here

  2. Select ADO.NET Entity Data Model and give it a name enter image description here

  3. Select EF Designer from database and click Next enter image description here

  4. Click New Connection enter image description here

  5. Configure your connection, click OK and click Next enter image description here

  6. Select Entity Framework version and click next enter image description here

  7. Select Databases and Tables to be connected and Click Finish enter image description here

4) Add Controllers to communicate with models

  1. Rebuild your project before doing forther enter image description here

  2. Add new Controller in Controllers folder enter image description here

  3. Select Web API 2 Controller with actions, using Entity Framework and click Add enter image description here

  4. Select Model class (table name) and Data context class (database name) from the drop-down list box and click Add enter image description here

5) Testing API

  1. Set this project as the startup project enter image description here

  2. Run the project in a web browser enter image description here

  3. Now your browser will open a localhost site. Click API in top enter image description here

  4. This page shows all the API available from your project enter image description here

  5. Copy any API link from below and replace it with the "Help" in URI and press Enter. Now you should able to see your data from the SQL Server database enter image description here

2. Serialize and Deserialize JSON data

1) Install Newtonsoft.Json

2) Deserializing JSON

HttpClient httpClient = new HttpClient();
var jsonReponse = await httpClient.GetStringAsync("http://localhost:xxxxx/api/LogIns");
logInResult = JsonConvert.DeserializeObject<List<LogIn>>(jsonReponse);

You can get the model class from Models enter image description here

Just create the same class in your UWP project

3) Serializing JSON

var logIn = new Models.LogIn()
{
    Username = "username",
    Password = "password"
};
var logInJson = JsonConvert.SerializeObject(logIn);

HttpClient httpClient = new HttpClient();
var httpContent = new StringContent(logInJson);
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

await httpClient.PostAsync("http://localhost:56267/api/LogIns", httpContent);

For more info about JSON Serialization And Deserialization Using JSON.NET Library In C#

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.