在Xamarin.Forms中直接访问Sql Server数据库

Jay*_*sta 1 c# database sql-server xamarin xamarin.forms

我只是一个使用Xamarin的初学者.我在Visual Studio 2013中创建了一个示例Xamarin.Forms Portable项目.我想知道是否可以访问MS SQL数据库并将其显示到我的手机上?如果是的话,你能告诉我一些如何做到这一点的指示吗?非常感谢.我希望有人会帮助我.

Geo*_*kis 6

您无法直接从Xamarin.Forms中的pcl项目访问sql server,因为System.Data.SqlClient在pcl上不可用.

但是你可以通过依赖服务来实现.

首先在您的PCL项目中声明您的服务

public interface IDbDataFetcher
    {
        string GetData(string conn);
    }
Run Code Online (Sandbox Code Playgroud)

然后在你的Android项目上实现服务接口

[assembly: Dependency(typeof(DbFetcher))]
namespace App.Droid.Services
{
    class DbFetcher : IDbDataFetcher
    {

        public List<string> GetData(string conn)
        {
            using (SqlConnection connection = new SqlConnection(conn))
            {

                SqlCommand command = new SqlCommand("select * from smuser", connection);
                try
                {
                    connection.Open();
                    SqlDataReader reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                        data.Add(reader[0].ToString());
                    }
                    reader.Close();
                }
                catch (Exception ex)
                {
                    //Console.WriteLine(ex.Message);
                }
            }
            return data;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

虽然这是一个解决方案,但它很糟糕.始终为您的移动应用程序使用Web服务