0

I have a xamarin.forms project. In the PCL I have a class with these 3 lines of code ....

1) SqlCommand cmd = new SqlCommand(); .... (Note: this line of code works)

2) cmd.Parameters.Add(new SqlParameter("@UserID", SqlDbType.Char, 5)).Direction = ParameterDirection.Input; .... (Note: this line of code works)

3) var userid = cmd.Parameters["@UserID"].Value; .... (Note: this line of code DOES NOT work)

I am receiving this message ...

"Reference by type "MarshalByRefObject" claims it is defined in 'mscorlib', but could not be found

these 3 lines of code work in the Android specific project but not in the PCL class

I can ADD the parameters to the SqlCommand in the PCL class but CANNOT retrieve a value

thanks in advance for your help

Mohamad Mahmoud Darwish
  • 3,865
  • 9
  • 51
  • 76
trent
  • 1
  • 1
  • What is the full namespace of the `SqlCommand`? Did you reference any lib in PCL? – Elvis Xia - MSFT Mar 13 '17 at 02:40
  • The full namespace = System.Data.SqlClient.SqlCommand .... i referenced the System.Data.dll in ... C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\MonoAndroid\v1.0 – trent Mar 13 '17 at 13:05

1 Answers1

0

The full namespace = System.Data.SqlClient.SqlCommand .... i referenced the System.Data.dll in ... C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\MonoAndroid\v1.0

The DLL you referenced is for Mono.Android project only, not for a PCL project. It can not be used in a PCL project. For explaination, please refer to this case.

If you want to use Native Android SQLite in PCL, please use Dependency Service:

  1. In your PCL Project. Create an interface(ISQLDb) for your Dependency Service and use the Service with DependencyService.Get<ISQLDb>():

    public interface ISQLDb
    {
        void InitCmd();
    }
    
    private void btnClick_Clicked(object sender, EventArgs e)
    {
        //use the service any where in your PCL project
        ISQLDb db=DependencyService.Get<ISQLDb>();
        db.InitCmd();
    }
    
  2. Create a class for Service Implementation in Mono.Android project and register it as Dependency Service:

    //register the Dependency Service
    [assembly:Xamarin.Forms.Dependency(typeof(SQLDbImpl))]
    namespace SQLCommandDemo.Droid
    {
        //implements the ISQLDb Interface
        public class SQLDbImpl : ISQLDb
        {
            public void InitCmd()
            {
                SqlCommand cmd = new SqlCommand();
                cmd.Parameters.Add(new SqlParameter("@UserID", SqlDbType.Char, 5)).Direction = ParameterDirection.Input;
                var userid = cmd.Parameters["@UserID"].Value;
            }
        }
    }
    
Community
  • 1
  • 1
Elvis Xia - MSFT
  • 10,801
  • 1
  • 13
  • 24