Search code examples
c#sql-serverdatabaseblazor-server-sidedata-access-layer

how to Get by Id data from database Blazor C#


already have started crud with blazor serverside to get data from database

i am working now to create a page where i will see details and edit one item of a list

i got the id of the item i want to display but my crud solution give me a list of object not just one llike i need....

i got my SqlDataAccess where i code the two main function (load -> QueryAsync, and Save -> ExecuteAsync) with its interface like below :

enter image description here

And i got a FiledbData class from where i call db like below :

enter image description here

i want now just to ask the database for one item like an getbyId instead of get all data ...


Solution

  • You can use parameterized queries to execute an where clause.

    Therefore the GetFile method would be like this:

    public Task<FileModel> GetFilebyId(int id)
    {
        string sql = "select * from dbo.file.. where Id = @Id";
        return _db.LoadSingleResult<FileModel, dynamic>(sql, new  {Id = id });
    }
    

    Also you need to add a new method LoadSingleResult like below(other parts apart from try section are similar to your LoadData method):

    public async Task<T> LoadSingleResult<T,U>(string sql, U parameters)
    {
       .
       .
       .
       try{
           var data=await connection.QueryAsynch<T>(sql, parameters);
           reurn data.Single();
       }
       .
       .
       .
    }
    

    Note that:

    • The id column assumed to be Id.
    • The id column assumed to be an integer column

    You can use QuerySingleOrDefaultAsync too.