Reputation: 479
I want to use my function like lambda inline of my code. But i don't know how to write it.
public Task<Product> Details(string id)
{
return Task.FromResult(GetProduct(id));
}
private Product GetProduct(string id)
{
try
{
var employee = db.ProductList
.Include(d => d.MappingProductTagList)
.ThenInclude(mapping => mapping.Tag)
.SingleOrDefault(p => p.Id == id);
db.Entry(employee).State = EntityState.Detached; // Änderungen werden nicht geprüft.
return employee;
}
catch
{
throw;
}
}
I want so use the code like this. But i get the Message "Cannot convert lambda expression to type 'Product' because it is not a delegate type"
public Task<Product> Details(string id)
{
return Task.FromResult<Product>(() => {
Product employee = db.ProductList
.Include(d => d.MappingProductTagList)
.ThenInclude(mapping => mapping.Tag)
.SingleOrDefault(p => p.Id == id);
db.Entry(employee).State = EntityState.Detached; // Änderungen werden nicht geprüft.
return employee;
});
}
Upvotes: 0
Views: 1075
Reputation: 270
Task.FromResult<Product>()
expects a parameter of type Product
, so you can't pass a lambda expression, hence the compile error.
Upvotes: 1
Reputation: 3629
Try the following, though I'm not entirely sure what you are trying to accomplish. You are already giving a valid example of how to use Task.FromResult
right at the start. But you are asking how to do it with a lambda (I don't understand why). I'm simply assuming you want to defer the execution into an actual Task, which is what I'm demonstrating below:
public Task<Product> Details(string id)
{
return Task.Run(() =>
{
Product employee = db.ProductList
.Include(d => d.MappingProductTagList)
.ThenInclude(mapping => mapping.Tag)
.SingleOrDefault(p => p.Id == id);
db.Entry(employee).State = EntityState.Detached; // Änderungen werden nicht geprüft.
return employee;
});
}
Upvotes: 1