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 :
And i got a FiledbData class from where i call db like below :
i want now just to ask the database for one item like an getbyId instead of get all data ...
CodePudding user response:
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.
CodePudding user response:
Add a where
clause to your DB SQL query and create an overload of GetFiles() that takes an ID value which will be interpolated into the SQL query:
public Task<List<FileModel>> GetFile(Guid id)
{
string sql = $"select * from myTable where Id = '{id:D}'";
return _db.LoadData<FileModel, dynamic>(sql, new { });
}