public async Task<ServiceResponse<Product>> GetProductAsync(int productId)
{
var response = new ServiceResponse<Product>()
{
Data = await _context.Products.AsNoTracking().FirstOrDefaultAsync(p => p.Id == productId)
} ;
if ( response.Data == null )
{
response.Success = false ;
response.Message = "Sorry, but this product does not exist." ;
}
else
return response ;
return response ;
}
I made productservice.cs file
. The above code is the part of it which will return one product class in Gerelic T.
First, I find matched productid in db. Then, null check. If it is not null it will return response, OK.
I thought at first I will return response as one product to Task
T
, all code might be good.
But I faced an error in the last line, so I put again return response
. Then the error sign was disappeared.
I think this might be wrong and weird, even though there is no error anymore. How can I solve this problem efficiently?
The error you faced probably was something like not all code paths return a value
. Since your method returns a typed value, and you are using if-else
statement -- you have to provide returning value both in if
and else
clauses.
ServiceResponse<T>
with a constructor that receives some arguments.product
variable for better readability.ServiceResponse
using newly-created constructor.Unfortunately, I can't test it right now to be sure 100%, but you can give it a try.
class ServiceResponse<T>
{
public T Data { get; set; }
public bool IsSuccess { get; set; }
public string Message { get; set; }
public ServiceResponse( T data, string message = "success" )
{
Data = data;
IsSuccess = data != null;
Message = data == null ? "Sorry, but this product does not exist." : message;
}
}
public async Task<ServiceResponse<Product>> GetProductAsync( int productId )
{
var product = await _context.Products.Where( p => p.Id == productId).AsNoTracking().FirstOrDefault();
return new ServiceResponse<Product>( product );
}
Remarks
message
in the constructor. But you still can do that!message
there if data == null
. Actually, it can be removed if you wish!IsSuccess
is also being regulated by data
in the constructor of ServiceResponse<T>
UPD: Tested
if ProductId == 1
{
"data": {
"id": 1,
"name": "Test1"
},
"isSuccess": true,
"message": "success"
}
if ProductId == 2 (which is out of list)
{
"data": null,
"isSuccess": false,
"message": "Sorry, but this product does not exist."
}