简体   繁体   中英

.NET Core Entity Framework stored procedures

I'm trying to port a ASP.NET 4.5 application to .NET Core and I have one real issue I can't seem to figure out.

My existing application executes stored procs which return a dataset with multiple datatables. The Entity Framework can automatically map the returned fields to my entity properties but only works with the first datatable in the dataset (naturally).

So I'm just trying to figure out if its at all possible to somehow intercept the model building process and use custom code to process the dataset and look into the other datatables to set entity fields.

I know I can use the normal way of executing the stored procedure directly using the SqlConnection but I'm wondering if the Entity Framework has some way to do this already.

At the moment, the way to execute stored procedures that return data is to use the DbSet.FromSql method.

using (var context = new SampleContext())
{
    var data= context.MyEntity
        .FromSql("EXEC GetData")
        .ToList();
}

This has certain limitations:

  • It must be called on a DbSet
  • The returned data must map to all properties on the DbSet type
  • It does not support ad hoc objects.

Or you can fall back to plain ADO.NET:

using (var context = new SampleContext())
using (var command = context.Database.GetDbConnection().CreateCommand())
{
    command.CommandText = "GetData";
    command.CommandType = CommandType.StoredProcedure;
    context.Database.OpenConnection();
    using (var result = command.ExecuteReader())
    {
        // do something with result
    }
}

There are plans to introduce support for returning ad hoc types from SQL queries at some stage.

Plain ADO.NET Code would be as follows to consume the stored procedure. By using DataAdaptor:

            DataSet dataSet = null;

            using (var context = new SampleContext())
            using (var command = context.Database.GetDbConnection().CreateCommand())
            {
                command.CommandText = "GetData";
                command.CommandType = CommandType.StoredProcedure;
                context.Database.OpenConnection();
                using (SqlDataAdapter adapter = new SqlDataAdapter())
                {
                    adapter.SelectCommand = command;

                    dataSet = new DataSet();
                    adapter.Fill(dataSet);
                    return dataSet;
                }
            } 

I used StoredProcedureEFCore nuget package by https://github.com/verdie-g/StoredProcedureEFCore,EnterpriseLibrary.Data.NetCore,EFCor.SqlServer,EFCore.Tools

I tried DbFirst approach with {Repository pattern}.. i think so

startup.cs

ConfigureServices(IServiceCollection services){
    services.AddDbContext<AppDbContext>(opt => opt
                   .UseSqlServer(Configuration.GetConnectionString("SampleConnectionString")));
    services.AddScoped<ISomeDAL, SomeDAL>();

}
            
    public  class AppDbContext : DbContext{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
    {}
}

ISomeDAl Interface has {GetPropertiesResponse GetAllPropertiesByCity(int CityId);}

public class SomeDAL : ISomeDAL
{
     private readonly AppDbContext context;

     public SomeDAL(AppDbContext context)
         {
             this.context = context;
         }
     public  GetPropertiesResponse GetAllPropertiesByCity(int CityId)
     {
         //Create Required Objects for response 
         //wont support ref Objects through params
         context.LoadStoredProc(SQL_STATEMENT)
            .AddParam("CityID", CityId).Exec( r =>
             {
                  while (r.Read())
                  {

                       ORMapping<GenericRespStatus> orm = new  ORMapping<GenericRespStatus>();
                       orm.AssignObject(r, _Status);
                  }

                  if (r.NextResult())
                  {

                       while (r.Read())
                       {
                           Property = new Property();
                           ORMapping<Property> orm = new ORMapping<Property>();
                           orm.AssignObject(r, Property);
                           _propertyDetailsResult.Add(Property);
                       }
                  }    
           });
    return new GetPropertiesResponse{Status=_Status,PropertyDetails=_propertyDetailsResult}; 
    }
}

public class GetPropertiesResponse
{
     public GenericRespStatus Status;
     public List<Property> PropertyDetails;
     public GetPropertiesResponse()
         {
             PropertyDetails = new List<Property>();
         }
}
public class GenericRespStatus
{
     public int ResCode { get; set; }
     public string ResMsg { get; set; }
}
internal class ORMapping<T>
{
    public void AssignObject(IDataReader record, T myClass)
    {
        PropertyInfo[] propertyInfos = typeof(T).GetProperties();
        for (int i = 0; i < record.FieldCount; i++)
        {
            if (propertyInfos.Any(obj => obj.Name == record.GetName(i))) //&& record.GetValue(i) != DBNull.Value
            {
                propertyInfos.Single(obj => obj.Name == record.GetName(i)).SetValue(myClass, Convert.ChangeType(record.GetValue(i), record.GetFieldType(i)));
            }
        }
    }
}

To answer @DKhanaf's issue with multiple datasets, you can use the SqlDataAdapter to fill a DataSet object with all of your resultsets. SqlDataAdapter requires the full .NET Framework though, so you'd have to run your .NETCore project while targeting .NET 462 or something similar.

         using (var context = new SampleContext())
            using (var command = context.Database.GetDbConnection().CreateCommand())
            {
                command.CommandText = "GetData";
                command.CommandType = CommandType.StoredProcedure;
                context.Database.OpenConnection();
                using (SqlDataAdapter adapter = new SqlDataAdapter(command))
                {
                    var ds = new DataSet();
                    adapter.Fill(ds);
                    return ds;
                }

            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM