I want to write raw SQL to get a result sets from a set of tables where there is 1-to-M relationship.
I am using Dapper for this, but not getting the expected results.
The first table is Supplier
:
public class Supplier: IId
{
public int Id { get; set; }
public string Ref{ get; set; }
public DateTime CreatedOn { get; set; }
public List<Category> Categories{ get; set; }
public int? Ticket { get; set; }
}
Then there's Category
:
public class Category: IId
{
public int Id { get; set; }
public int SupplierId{ get; set; }
[JsonIgnore] public Supplier Supplier{ get; set; }
public Type Type { get; set; }
public Status Status { get; private set; }
public string CompletedBy { get; private set; }
public string CreatedBy { get; private set; }
public DateTime? CreatedOn { get; private set; }
public int? Ticket { get; set; }
}
Here is my SQL:
var reference = 5055;
var sql = "SELECT S.Ref,S.CreatedOn,S.Ticket" +
" C.TaskId AS 'Id', C.SupplierId, C.Type, C.Status, C.CompletedBy, C.CreatedBy, C.CreatedOn, C.Ticket " +
"FROM Category C " +
"INNER JOIN Supplier S ON S.SupplierId = C.SupplierId " +
"WHERE S.Ref = @reference ";
var parameters = new {reference};
var suppliers = connection.QueryAsync<Supplier, List<Category>, Supplier>(sql, (supplier,category) => {
supplier.Categories = category;
return supplier;
}, parameters, splitOn: "Id" );
var result = suppliers.Result.OrderByDescending(x => x.CreatedOn).FirstOrDefault();
What I want is categories should be included in supplier entity, I read the documentation for Dapper and from that I tried the code shown here, but it's not working out.
Can anybody help me with this?
Can anybody tell me another approach for this, for example with a SQL view or a stored procedure?
how i found a way to solve this is