Search code examples
c#entity-frameworklinqlinq-to-entities

Second result set returns null values - linq to entities


When I created my entity I imported a stored procedure which returns two data sets. While researching I found how to accommodate this using only code and not modifying the entity model xml. I've done this and now my first data set is populated correctly. My second data set correctly returns 1 row, but the values are empty. I made sure that the objects keys were the same (case and spelling) as what the store procedure returns.

My resources:

  1. Issue when trying to read multiplte entity resultsets from a stored procedure
  2. How to get Multiple Result Set in Entity Framework using Linq with C#?
  3. https://msdn.microsoft.com/en-us/library/jj691402(v=vs.113).aspx.

My Code:

public class oEngine
{
    public string Engine;
    public DateTime ResultsDateTime;
}

...

// If using Code First we need to make sure the model is built before we open the connection
// This isn't required for models created with the EF Designer
ctx.Database.Initialize(force: false);

// Create a SQL command to execute the sproc
var cmd = ctx.Database.Connection.CreateCommand();
cmd.CommandText = "[dbo].[usp_IntMonDisplay]";

try
{
    ctx.Database.Connection.Open();
    // Run the sproc 
    var reader = cmd.ExecuteReader();

    // Read Blogs from the first result set
    reply.results = ((IObjectContextAdapter)ctx).ObjectContext.Translate<Entities.usp_IntMonDisplay_Result>(reader).ToList();

    // Move to second result set and read Posts
    reader.NextResult();
    reply.engines = ((IObjectContextAdapter)ctx).ObjectContext.Translate<oEngine>(reader).ToList();

}
finally
{
    ctx.Database.Connection.Close();
}

Solution

  • The problem is that your oEngine class has public fields while EF maps (works) only with properties.

    Change it to

    public class oEngine
    {
        public string Engine { get; set; }
        public DateTime ResultsDateTime { get; set; }
    }
    

    and the issue will be solved.