如何从存储过程中检索与外键连接的数据库中的对象集合

时间:2015-11-21 08:35:42

标签: sql-server entity-framework tsql stored-procedures

从应用程序,我调用存储过程

IEnumerable<ObjectA> AList = this.Context.Database.SqlQuery<A>
      ("EXEC [MyProcedure] @PageSize, @PageNumber, @C, @D, parameters);

原因或那就是我从app传递整数列表,而在数据库中我有TVP用于制作它们。现在,让我们说我在应用程序中的课程看起来像这样

  class A{
   public int ID{get; set;}
   ....
    public virtual ICollection<B> BList{ get; set; } }

在我的程序中,我选择

      Select distinct TableA.*,
             TableB.Id, TableB.Name

但是,在我的应用中,对象A在其集合中没有任何objectB。如何从我的过程中选择从对象A中的集合中获取TableB中的对象?

1 个答案:

答案 0 :(得分:1)

您的程序需要“多个结果集”。

https://msdn.microsoft.com/en-us/data/jj691402.aspx

Select a.Column1, a.Column2, a.Column3 from dbo.TableA a where (your input parameters as filters on TableA)

Select b.Column1, b.Column2, b.Column3, b.Column4, b.TableAColumn1FK from dbo.TableB b where exists ( select null from dbo.TableA a where a.Column1 = b.TableAColumn1FK and (your input parameters as filters on TableA)

EF伪代码

using (var db = new MyContext()) 
{ 
    // 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 
    db.Database.Initialize(force: false); 

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

    try 
    { 

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

        // Read Blogs from the first result set 
        var tableAThings = ((IObjectContextAdapter)db) 
            .ObjectContext 
            .Translate<TableA_EFPoco>(reader, "TableA", MergeOption.AppendOnly);    




        // Move to second result set and read Posts 
        reader.NextResult(); 
        var tableBThings = ((IObjectContextAdapter)db) 
            .ObjectContext 
            .Translate<TableB_EFPoco>(reader, "TableBs", MergeOption.AppendOnly); 



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

注意:EF在使用Translate方法创建实体时不会考虑任何映射。它只是将结果集中的列名与类上的属性名匹配。

相关问题