Pregunta

I have a stored procedure that does something similar to:

SELECT a.TaskId, b.CompanyCode FROM task a JOIN company b ON b.CompanyId = a.CompanyId;

I have an object called TaskItem that has the TaskId and CompanyCode properties, but when I execute the following (which I would have assumed worked):

        var masterDatabase = new Database("MasterConnectionString");
        var s = PetaPoco.Sql.Builder.Append("EXEC spGetTasks @@numberOfTasks = @0", numberOfTasks);
        var tasks = masterDatabase.Query<TaskItem>(s);

The problem is that the CompanyCode column does not exist in the task table, I did a trace and it seems that PetaPoco is trying to select all the properties from the task table and populating using the stored procedure.

Here is a definition of TaskItem:

public class TaskItem {
    public int TaskItemId { get; set; }
    public int CompanyId { get; set; }
    public string CompanyCode { get; set; }
    public int Status { get; set; }
}

How can I use PetaPoco to simply populate the list of task objects with the results of the stored procedure?

¿Fue útil?

Solución

If you only need two columns from the database, don't bother with POCOs. Use dynamic:

var d = masterDatabase.Query<dynamic>("Exec spGetTasks @@numberOfTasks = @0", numberOfTasks);
var result = d.Select(item => new Tuple<int, string>(item.TaskId, item.CompanyCode)).ToList();

otherwise the POCO that you are using to query database, i.e. TaskItem need to have a public property for each column name returned by the query.

UPDATE Now that you've posted definition of TaskItem I see that you have all the properties that you need on it. In theory it is enough to have a public property with the exact same name as the returned column for it to be populated. So in your case since query returns column CompanyCode, the appropriate property should be populated on the TaskItem. In case the property name differs, you can map it by decorating it with [Column] attribute

[Column("NameOfTheColumn")]
public string CompanyCode { get; set; }

If for some reason CompanyCode still remains not populated, the issue is with the query. Make sure that it returns appropriate results.

Otros consejos

Besides using dynamic as @Dmitry points, you can add the property to the TaskItem POCO, and decorate it with ResultColumn

    [ResultColumn]
    public string CompanyCode { get; set; }
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top