如何将存储过程作为IQueryable?

时间:2016-03-06 06:11:03

标签: c# entity-framework stored-procedures linq-to-entities where-clause

我希望从实体获取存储过程,以防我可以这样使用:

var WagonQuery = db.spGetTravelBYRTravelInfo(DepartureDate, FromId, ToId);

if (WagonId != 0)
    WagonQuery = WagonQuery.Where(p => p.WagonID == WagonId); // HERE IS ERROR. Wagonquery Can Not Uses Like forexample List,So I Can Filter It And Use Several Where Clauses

grdTravels.DataSource = WagonQuery;
grdTravels.DataBind();

这是错误:

  

无法隐式转换类型' System.Collections.Generic.IEnumerable' to' System.Data.Objects.ObjectResult'。存在显式转换(您是否错过了演员?)

2 个答案:

答案 0 :(得分:0)

我应该将它转换为列表然后(就像这样):

        List<spGetTravelBYRTravelInfo_Result> lst = db.spGetTravelBYRTravelInfo(DepartureDate, FromId, ToId).ToList();
    var dt = lst.Select(p => p);
    if (WagonId != 0)
        dt = dt.Where(p => p.WagonID == WagonId);
    if (ddlReserved.SelectedValue == "t")
        dt = dt.Where(p => p.Presell > 0);

答案 1 :(得分:0)

我无法弄清楚存储过程返回的内容。在我使用EF 6.1.3的项目中,您可以通过以下操作从数据库中动态过滤列表

 List<SparePart> spSpares = db.Database.SqlQuery<SparePart>("spGetSparePartsFromProductId " + Convert.ToString(productId) + "," + Convert.ToString(subProduct));

我的模特在哪里

 public partial class SparePart
    {
        public long ItemID { get; set; }
        public string ItemCode { get; set; }
        public string ItemName { get; set; }
        public Nullable<decimal> ItemPrice { get; set; }
        public bool IsActive { get; set; }
        public string ItemDesc { get; set; }
        public Nullable<int> ItemGroup { get; set; }
        public string Model { get; set; }
        public string MajorCategory { get; set; }
        public string MinorCategory { get; set; }
        public string UOM { get; set; }
    }

和存储过程

CREATE PROC [dbo].[spGetSparePartsFromProductId]
(
@productId bigint,
@subproductId bigint=0
)
AS
BEGIN
if @productId=1 
select * from SpareParts
END 
GO

与SpareParts表相同的结果

Same as Model

可能是一些帮助