Connect SQL Server using .NET MAUI and perform CRUD operations

zc0qhyus  于 2023-05-16  发布在  SQL Server
关注(0)|答案(1)|浏览(171)

I'm need some guidance on how to connect .NET MAUI with my local SQL Server database. I've been using C# WinForms and SQL Server for a while now, but I'm not sure how to proceed with .NET MAUI.

My goal is to perform some CRUD operations from an Android emulator to my local SQL Server database. I'd really appreciate any advice on how to achieve this. If I need to write an API for this scenario, I'd love some help with that as well.

Thank you in advance for your help!

I have tried connect the SQL Server database directly using Microsoft.Data.SqlClient; but it works only on windows machine, but not in android emulator.

t98cgbkg

t98cgbkg1#

As someone said, usually you don't call it directly for security reasons. But If yo are just looking to test then you can do it just like you do it locally:

Write a service for retrieving an object:

public static class UserService
{
    private const string server = "";
    private const string database = "";
    private const string username = "";
    private const string password = "";

    private static string connectionString => $"Data Source={server};Database={database};User Id={username};Password={password}";

    public static async Task<UserDto> GetUserAsync(string username, string password, CancellationToken cancellationToken)
    {
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();

            string sql = "SELECT * FROM MyTable WHERE Column = @value";
            return await connection.QueryFirstOrDefaultAsync<UserDto>(sql).ToList();
        }
    }
}

Then in your button call just call the service:

var user = UserService.GetUserAsync("John Doe", "abcd1234");

相关问题