【发布时间】:2016-02-16 00:32:15
【问题描述】:
我有一个 ASP.NET MVC 站点,我想显示存储过程的一些详细信息。我之前在同一个应用程序的不同页面上对其他存储过程做过完全相同的事情并且它已经工作了,但是这个存储过程调用返回一个空对象而不是预期值。
EF 调用存储过程:
public MostRecentOrderDetail GetMostRecentOrder(int userId)
{
var context = new myDatabaseContext();
var paramUserId = new SqlParameter { ParameterName = "viUserId", Value = userId };
var result = context.Database.SqlQuery<MostRecentOrderDetail>("usp#GetMostRecentOrder @viUserId", paramUserId).FirstOrDefault();
return result;
}
在我的控制器中,我使用以下方法调用它:
MostRecentOrderDetail latestOrder = myDB.GetMostRecentOrder(CurrentUser.UserId).FirstOrDefault();
当我在 SQL Server Management Studio 中调用存储过程时,它返回一个填充了正确值的单行表,我似乎无法让我的 ASP.NET MVC 站点看到它。
MVC 站点使用代码优先,MostRecentOrderDetail 对象正确映射到存储过程的列。
*编辑
我已按照下面的@DanielDrews 建议更新了我的代码,现在收到一个异常,我认为这是向前迈出的一步:
The data reader is incompatible with the specified 'MyApp.Models.MostRecentOrderDetail'. A member of the type, 'OrderTypeCode', does not have a corresponding column in the data reader with the same name.
我相信我的模型映射正确。
myDatabaseContext.cs
public partial class myDatabaseContext : DbContext
{
// Database Initializer etc
public IDbSet<MostRecentOrderDetail> MostRecentOrderDetails { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// ... Other Maps
modelBuilder.Configurations.Add(new MostRecentOrderMap());
}
// GetMostRecentOrder() function from above
}
MostRecentOrderMap.cs
public class MostRecentOrderMap : EntityTypeConfiguration<MostRecentOrderDetail>
{
public MostRecentOrderMap()
{
// Table and Column Mappings
this.ToTable("usp#GetMostRecentOrder");
this.Property(t => t.OrderTypeCode).HasColumnName("order_type_code");
this.Property(t => t.OrderStatusCode).HasColumnName("order_status_code");
this.Property(t => t.OrderReceivedDate).HasColumnName("order_received_date");
this.Property(t => t.OrderShippedDate).HasColumnName("order_shipped_date");
}
}
MostRecentOrderDetail.cs
public class MostRecentOrderDetail
{
[Key]
public string OrderTypeCode { get; set; }
public string OrderStatusCode { get; set; }
public DateTime OrderReceivedDate { get; set; }
public DateTime OrderShippedDate { get; set; }
}
存储过程本身:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[usp#GetMostRecentOrder]
@viUserId int
AS
begin
SELECT TOP 1 o.order_type_code,
o.order_status_code,
o.order_received_date,
o.order_shipped_date
FROM ORDER_TABLE o
WHERE o.user_id = @viUserId
end
【问题讨论】:
-
UserId肯定被正确传递了? -
@Papa 是的,据我所知它正在通过它,
return行上的断点显示UserID具有Base: @viUserId , DBType: Int32, Value: 1234(我的测试用户ID)。我似乎无法检查正在执行的实际查询。
标签: c# asp.net-mvc entity-framework stored-procedures