首页 文章

如何从Windows 10 UWP应用程序连接到SQL Server数据库

提问于
浏览
11

我使用UWP制作LOB应用程序,以支持桌面,平板电脑和移动应用 . 当尝试连接到本地(Intranet)SQL Server数据库时,我习惯使用SqlConnection的实例连接到本地服务器,但由于SqlConnection不包含在UWP中使用的.NET子集中,如何完成什么时候使用UWP?

我查看了official Microsoft samples以及how-to guides,并没有发现任何关于不是Azure数据库的数据库连接 . DbConnection似乎可能是一个很好的方法,但是它可以是抽象的,它的子节点(例如Data.SqlClient.SqlConnection)似乎不包含在UWP的.NET子集中 .

我错过了一些非常明显的东西吗?顺便说一下,有没有人知道UWP的良好命名空间参考?

编辑非重复:建议重复的链接问题适用于Windows 8 / 8.1应用程序,虽然有一些相似之处,但该问题的已接受答案中的代码将无法在UWP上运行 . 但原则是相同的,但对于使用UWP构建的Windows 10应用程序应该有更好的技术参考 .

4 回答

  • 4

    借助Windows 10 Fall Creators Update(内部版本16299),UWP应用程序现在可以通过标准的.NET类(System.Data.SqlClient)直接访问SQL Server - 这要归功于UWP中新增的.NET Standard 2.0支持 .

    这是一个Northwind UWP演示应用程序:https://github.com/StefanWickDev/IgniteDemos

    我们已于2017年9月在Microsoft Ignite上演示了此演示,这里是我们会话的录制(对于SQL演示,请跳至23:00):https://myignite.microsoft.com/sessions/53541

    以下是从Northwind数据库中检索产品的代码(请参阅演示中的DataHelper.cs) . 请注意,它与您为Winforms或WPF应用程序编写的代码完全相同 - 得益于.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;
    }
    

    如果您需要支持早于Fall Creators Update的早期版本,还可以通过桌面桥从UWP应用程序包中调用SqlClient API . 我在这里发布了一个样本:https://github.com/Microsoft/DesktopBridgeToUWP-Samples/tree/master/Samples/SQLServer

  • 10

    这是simple samplea video . 不确定它是否足够你 .

    这是一个难点

    • 如何使用,序列化和反序列化json数据 . 作为.net开发人员,您可以考虑使用HttpClient来实现它 . 这里有another samplevideo供您参考 . 有another official sample显示了如何使用Windows.Data.Json命名空间 .
  • 1

    我不得不走同样的道路......期待直接通过EF Core直接访问SQLServer .

    我已经看过上面的两个教程,因为我刚开发,它只会影响我的胃口 . 然而,我确实在YouTube上发现了这个详细的Video Tutorial,它会引导您走过;

    • 创建WebService

    • 在WebService和您的UWP应用程序中创建重复的POGO类

    • 为要创建的每个表创建Web API 2.0实体框架控制器

    • 通过NuGet将Newtonsoft.JSON和Microsoft.Net.HTTP添加到您的UWP应用程序

    • 并最终通过Code Behind中的Web Service / JSON调用从UWP调用回本地SQL Server .

    尽管这个视频不是英文的,但我能够看到他在做什么然后暂停和复制 .

  • 2

    将UWP连接到SQL Server

    注意:从Windows 10 Fall Creators Update(16299)我们可以使用.NetStanded 2.0直接访问SQL Server数据库

    由于没有直接的方法连接到SQL Server,我们需要为我们的数据库创建一个API才能连接到SQL Server .

    该解决方案描述

    • Creating API

    • Serialize and Deserialize JSON data

    1.创建API

    1)安装ASP.NET和Web开发

    • 启动 Visual Studio Installer 并单击 Modify
      enter image description here

    • 安装 ASP.NET and web development
      enter image description here

    2)创建新的ASP.NET Web应用程序(.Net Framework)

    • Add new project 在你的解决方案中
      enter image description here

    • Select ASP.NET Web Application (.Net Framework) 并提供项目名称
      enter image description here

    • Select Web API 并单击确定
      enter image description here

    3)连接到SQL Server数据库

    模型文件夹中的

    • Add new item
      enter image description here

    • Select ADO.NET Entity Data Model 并命名为
      enter image description here

    • Select EF Designer from database 并单击下一步
      enter image description here

    • 点击 New Connection
      enter image description here

    • Configure your connection ,单击“确定”,然后单击“下一步”
      enter image description here

    • Select Entity Framework version 并单击下一步
      enter image description here

    • Select Databases and Tables 待连接并单击Finish
      enter image description here

    4)添加控制器以与模型通信

    • 重建你做之前的项目
      enter image description here

    控制器文件夹_279_ Add new Controller
    enter image description here

    • Select Web API 2 Controller with actions, using Entity Framework 并单击添加
      enter image description here

    • 从下拉列表框中选择 Model class (表名)和 Data context class (数据库名),然后单击添加
      enter image description here

    5)测试API

    • 将此项目设置为 startup project
      enter image description here

    • Run the project 在网络浏览器中
      enter image description here

    • 现在您的浏览器将打开一个localhost站点 . Click API 在顶部
      enter image description here

    • 此页面显示项目中可用的所有API
      enter image description here

    • 从下面复制任何API链接,并将其替换为URI中的"Help",然后按Enter键 . 现在您应该能够从SQL Server数据库中查看数据
      enter image description here

    2.序列化和反序列化JSON数据

    1)安装Newtonsoft.Json

    2)反序列化JSON

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

    你可以从Models
    enter image description here
    获得模型类

    只需在UWP项目中创建相同的类

    3)序列化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);
    

    有关JSON Serialization And Deserialization Using JSON.NET Library In C#的更多信息

相关问题