Getting error cannot implicitly convert from one Class to other

Kalyan A 205 Reputation points
2024-08-29T11:49:18.96+00:00

Classes Questionping and I Questionpin are same , but still I get error saying cannot implicitlyconvert Questionping to IQuestionpin

@inject NavigationManager Navigation
@using System.Text;
@using System.Net.Http.Headers;
@using Microsoft.AspNetCore.Components;
@using Newtonsoft.Json;
@using Microsoft.JSInterop;
@using MauiAppMCQs.Models;
@page "/Login"
<h3>Login</h3>
<EditForm Model="@submitActivity" OnSubmit="@Submit">
    <br />
    <div class="row">
        <div class="col-md-3">
            <p>PIN</p>
        </div>
        <div class="col-md-4">
            <input placeholder="PIN" @bind="@pin" />
        </div>
    </div>
    <div>
        <button type="submit">Submit</button>
    </div>
    <div>
        @errmsg
    </div>
</EditForm>
 
@code {
    private int pin; private string jwttoken; private string connected; private string jsonString;
    public string @errmsg = "";
    private ACTIVITY submitActivity { get; set; } = new();
    List<Questionpin> Questions = new List<Questionpin>();
    List<IQuestionpin> OQuestions = new List<IQuestionpin>();
    List<Questionpin> res;
    QuestionsDatabasepin questionsDatabasepin;
    public class Questionpin
    {
        public long Id { get; set; }
        public int Pinnum { get; set; }
    }
    public string matches;
    public class ACTIVITY
    {
        public string Dummy { get; set; }
    }
    private async void Submit()
    {
        questionsDatabasepin = new QuestionsDatabasepin();
        // Questions = list1;
        LoadQuestionsAsync();
        //    Questions = list1;
        var result = Questions.FirstOrDefault(c => c.Pinnum == pin);
        if (result == null)
        {
            errmsg = "Enter Valid  pin";
        }
        else
        { Navigation.NavigateTo("/NewNav", true); }
    }
    private async void LoadQuestionsAsync()
    { res = await GetApiData(); }
    async Task<List<Questionpin>> GetApiData()
    {
        var jsonContent = new StringContent(JsonConvert.SerializeObject(new
        {
            bodyField1 = ""
        }), Encoding.UTF8, "application/json");
        connected = "N";
        try
        {
            using (var client1 = new HttpClient())
            {
                string authurl = "https://myquizapi.azurewebsites.net/api/";
                client1.BaseAddress = new Uri(authurl);
                client1.DefaultRequestHeaders.Clear();
                client1.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage Res = await client1.PostAsync("Auth", jsonContent);
                if (Res.IsSuccessStatusCode)
                {
                    //Storing the response details recieved from web api
                    string json = await Res.Content.ReadAsStringAsync();
                    // Parse the JSON response to extract the address
                    dynamic data1 = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
                    jwttoken = data1.token;
                }
            }
            string apiUrl = "https://myquizapi.azurewebsites.net/api/";
            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri(apiUrl);
                client.DefaultRequestHeaders.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {jwttoken}");
                HttpResponseMessage response = null;
                response = await client.GetAsync("pins");
                // Check if the request was successful (status code 200)
                if (response.IsSuccessStatusCode)
                {
                    // Make a GET request to the API
                    connected = "Y";
                    // Read the content of the response
                    string jsonString = await response.Content.ReadAsStringAsync();
                    List<IQuestionpin> itemInTheDB = await questionsDatabasepin.GetItemsAsync();
                    // Deserialize the JSON string into an object
                    Questions = JsonConvert.DeserializeObject<List<Questionpin>>(jsonString);
                    foreach (IQuestionpin item in itemInTheDB)
                    {
                        var result = Questions.FirstOrDefault(c => c.Id == item.Id);
                        if (result == null)
                        {
                            await questionsDatabasepin.DeleteItemAsync(item);
                        }
                    }
                    OQuestions = JsonConvert.DeserializeObject<List<IQuestionpin>>(jsonString);
                    List<IQuestionpin> itemOutTheDB =   OQuestions;
                    foreach (IQuestionpin itemdb in itemOutTheDB)
                    {
                        var resulty = itemInTheDB.FirstOrDefault(c => c.Id == itemdb.Id);
                        matches = "N";
                        if (resulty == null)
                        { await questionsDatabasepin.SaveItemAsync(itemdb); }
                        if (resulty != null)
                        {
                            if ((resulty.Id == itemdb.Id) && (resulty.Pinnum == itemdb.Pinnum) )
                            { matches = "Y"; }
                        }
                        else
                        { await questionsDatabasepin.SaveItemAsync(itemdb); }
                        if (matches == "N")
                        { await questionsDatabasepin.SaveItemAsync(itemdb); }
                    }
                }
                else { OQuestions = await questionsDatabasepin.GetItemsAsync();
                    Questions = OQuestions;
                }
            }
        }
        catch (Exception ex)
        {
            if (connected == "N")
            {
                OQuestions = await questionsDatabasepin.GetItemsAsync();
                Questions = OQuestions;
            }
        }
        return Questions; }
}
using SQLite;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MauiAppMCQs.Models
{
    public class QuestionsDatabasepin
    {
        SQLiteAsyncConnection Database;
        private SQLiteAsyncConnection _dbConnection;
        public const string DatabaseFilename = "MCQpin.db3";
        async Task Init()
        {
            string dbPath =
             Path.Combine(FileSystem.AppDataDirectory, DatabaseFilename);
            FileStream fileStream = new FileStream(dbPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
            _dbConnection = new SQLiteAsyncConnection(dbPath);
            if (Database is not null)
                return;
            Database = new SQLiteAsyncConnection(dbPath, Constants.Flags);
            var result = await Database.CreateTableAsync<IQuestionpin>();
        }
        public async Task<List<IQuestionpin>> GetItemsAsync()
        {
            await Init();
            var res = await Database.Table<IQuestionpin>().ToListAsync();
            return res;
        }
        public async Task<IQuestionpin> GetItemAsync(long id)
        {
            await Init();
            return await Database.Table<IQuestionpin>().Where(i => i.Id== id).FirstOrDefaultAsync();
        }
        public async Task<long> SaveItemAsync(IQuestionpin item)
        {
            await Init();
            IQuestionpin res = await GetItemAsync(item.Id);
            if (res != null)
                return await Database.UpdateAsync(item);
            else
                return await Database.InsertAsync(item);
        }
        public async Task<int> DeleteItemAsync(IQuestionpin item)
        {
            await Init();
            return await Database.DeleteAsync(item);
        }
    }
}
namespace MauiAppMCQs.Models
{
   
        public class IQuestionpin
        {
            [PrimaryKey, Indexed]
            public long Id { get; set; }
            public int Pinnum { get; set; }
     
    }
}
.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
3,487 questions
0 comments No comments
{count} votes

Accepted answer
  1. Olaf Helper 44,501 Reputation points
    2024-08-29T12:12:43.0233333+00:00

    Classes Questionping and I Questionpin are same ,

    The classes defintions "look similar", but are far away from beeing the same. Even the case of ID/Id are different.

    You have to write an explict conversion.


1 additional answer

Sort by: Most helpful
  1. Kalyan A 205 Reputation points
    2024-08-29T16:48:16.4633333+00:00
    @inject NavigationManager Navigation
    @using System.Text;
    @using System.Net.Http.Headers;
    @using Microsoft.AspNetCore.Components;
    @using Newtonsoft.Json;
    @using Microsoft.JSInterop;
    @using MauiAppMCQs.Models;
    @page "/Login"
    <h3>Login</h3>
    <EditForm Model="@submitActivity" OnSubmit="@Submit">
        <br />
        <div class="row">
            <div class="col-md-3">
                <p>PIN</p>
            </div>
            <div class="col-md-4">
                <input placeholder="PIN" @bind="@pin" />
            </div>
        </div>
        <div>
            <button type="submit">Submit</button>
        </div>
        <div>
            @errmsg
        </div>
    </EditForm>
     
    @code {
        private int pin; private string jwttoken; private string connected; private string jsonString;
        public string @errmsg = "";
        private ACTIVITY submitActivity { get; set; } = new();
        List<Questionpin> Questions = new List<Questionpin>();
        List<IQuestionpin> OQuestions = new List<IQuestionpin>();
        List<Questionpin> res;
        QuestionsDatabasepin questionsDatabasepin;
        public class Questionpin
        {
            public long Id { get; set; }
            public int Pinnum { get; set; }
        }
        public string matches;
        public class ACTIVITY
        {
            public string Dummy { get; set; }
        }
        private async void Submit()
        {
            questionsDatabasepin = new QuestionsDatabasepin();
            // Questions = list1;
            LoadQuestionsAsync();
            //    Questions = list1;
            var result = Questions.FirstOrDefault(c => c.Pinnum == pin);
            if (result == null)
            {
                errmsg = "Enter Valid  pin";
            }
            else
            { Navigation.NavigateTo("/NewNav", true); }
        }
        private async void LoadQuestionsAsync()
        { res = await GetApiData(); }
        async Task<List<Questionpin>> GetApiData()
        {
            var jsonContent = new StringContent(JsonConvert.SerializeObject(new
            {
                bodyField1 = ""
            }), Encoding.UTF8, "application/json");
            connected = "N";
            try
            {
                using (var client1 = new HttpClient())
                {
                    string authurl = "https://myquizapi.azurewebsites.net/api/";
                    client1.BaseAddress = new Uri(authurl);
                    client1.DefaultRequestHeaders.Clear();
                    client1.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    HttpResponseMessage Res = await client1.PostAsync("Auth", jsonContent);
                    if (Res.IsSuccessStatusCode)
                    {
                        //Storing the response details recieved from web api
                        string json = await Res.Content.ReadAsStringAsync();
                        // Parse the JSON response to extract the address
                        dynamic data1 = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
                        jwttoken = data1.token;
                    }
                }
                string apiUrl = "https://myquizapi.azurewebsites.net/api/";
                using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress = new Uri(apiUrl);
                    client.DefaultRequestHeaders.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    client.DefaultRequestHeaders.Add("Authorization", $"Bearer {jwttoken}");
                    HttpResponseMessage response = null;
                    response = await client.GetAsync("pins");
                    // Check if the request was successful (status code 200)
                    if (response.IsSuccessStatusCode)
                    {
                        // Make a GET request to the API
                        connected = "Y";
                        // Read the content of the response
                        string jsonString = await response.Content.ReadAsStringAsync();
                        List<IQuestionpin> itemInTheDB = await questionsDatabasepin.GetItemsAsync();
                        // Deserialize the JSON string into an object
                        Questions = JsonConvert.DeserializeObject<List<Questionpin>>(jsonString);
                        foreach (IQuestionpin item in itemInTheDB)
                        {
                            var result = Questions.FirstOrDefault(c => c.Id == item.Id);
                            if (result == null)
                            {
                                await questionsDatabasepin.DeleteItemAsync(item);
                            }
                        }
                        OQuestions = JsonConvert.DeserializeObject<List<IQuestionpin>>(jsonString);
                        List<IQuestionpin> itemOutTheDB =   OQuestions;
                        foreach (IQuestionpin itemdb in itemOutTheDB)
                        {
                            var resulty = itemInTheDB.FirstOrDefault(c => c.Id == itemdb.Id);
                            matches = "N";
                            if (resulty == null)
                            { await questionsDatabasepin.SaveItemAsync(itemdb); }
                            if (resulty != null)
                            {
                                if ((resulty.Id == itemdb.Id) && (resulty.Pinnum == itemdb.Pinnum) )
                                { matches = "Y"; }
                            }
                            else
                            { await questionsDatabasepin.SaveItemAsync(itemdb); }
                            if (matches == "N")
                            { await questionsDatabasepin.SaveItemAsync(itemdb); }
                        }
                    }
                    else { OQuestions = await questionsDatabasepin.GetItemsAsync();
                        //   Questions = OQuestions;
                        foreach (IQuestionpin itemdb in OQuestions)
                        {
                            Questions.Add(new Questionpin { Id = itemdb.Id, Pinnum = itemdb.Pinnum });
                        }
                            }
                }
            }
            catch (Exception ex)
            {
                if (connected == "N")
                {
                    OQuestions = await questionsDatabasepin.GetItemsAsync();
                    foreach (IQuestionpin itemdb in OQuestions)
                    {
                        Questions.Add(new Questionpin { Id = itemdb.Id, Pinnum = itemdb.Pinnum });
                    }
                }
            }
            return Questions; }
    }
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.