我正在尝试从通用Windows应用程序连接到本地MS SQL数据库。我正在使用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应用程序,应该有更好的技术参考。
借助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更低的版本,还可以通过Desktop Bridge从UWP应用程序包中调用SqlClient API。我在这里发布了此示例:https://github.com/Microsoft/DesktopBridgeToUWP-Samples/tree/master/Samples/SQLServer
这里是simple sample和a video。不知道这是否足以满足您的需求。
我也必须走同样的路...期待可以直接通过EF Core直接访问SQLServer。