C# 当我在EF 5中使用这个存储过程时,它总是返回0
当我在EF 5中使用这个存储过程时,它总是返回0。 我认为其他程序没有问题C# 当我在EF 5中使用这个存储过程时,它总是返回0,c#,sql,entity-framework,visual-studio-2012,sql-server-2012,C#,Sql,Entity Framework,Visual Studio 2012,Sql Server 2012,当我在EF 5中使用这个存储过程时,它总是返回0。 我认为其他程序没有问题 ALTER proc [dbo].[ReadReviewCountByHotelId] @HotelId uniqueidentifier AS -- Returns the review count for given hotel. BEGIN SELECT Count(r.ReviewId) as ReviewCount FROM Review r WHERE r.Review_Hote
ALTER proc [dbo].[ReadReviewCountByHotelId]
@HotelId uniqueidentifier
AS
-- Returns the review count for given hotel.
BEGIN
SELECT Count(r.ReviewId) as ReviewCount
FROM Review r
WHERE r.Review_HotelId = @HotelId
END;
EF函数作为
public static int ReadReviewCountByHotelId(Guid? hotelId)
{
int reviewCount = 0;
try
{
var tEntities = new TravelEntities();
Int32.TryParse(tEntities.ReadReviewCountByHotelId(hotelId).ToString(),out reviewCount);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return reviewCount;
}
公共虚拟对象结果ReadReviewCountByHotelId(可为空的hotelId)
{
var hotelIdParameter=hotelId.HasValue?
新对象参数(“HotelId”,HotelId):
新的ObjectParameter(“HotelId”,typeof(System.Guid));
返回((IObjectContextAdapter)this.ObjectContext.ExecuteFunction(“ReadReviewCountByHotelId”,hotelIdParameter);
}
我在我的项目中使用EF。我第一次看到这个问题
感谢您的关注我不知道您是否真的输入了有效的id。但请尝试: 不计较 作为存储过程的第一行?这可能是罪魁祸首
一般来说,这是一个标量函数吗?更适合您的操作。未检查TryParse的返回值。如果以下行无法分析结果,则返回false,并且不会更改已初始化为零的reviewCount的值。它不会抛出异常
public virtual ObjectResult<Nullable<int>> ReadReviewCountByHotelId(Nullable<System.Guid> hotelId)
{
var hotelIdParameter = hotelId.HasValue ?
new ObjectParameter("HotelId", hotelId) :
new ObjectParameter("HotelId", typeof(System.Guid));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<Nullable<int>>("ReadReviewCountByHotelId", hotelIdParameter);
}
对结果的ToString()调用看起来可疑,因为返回值是T的ObjectResult。它似乎是可枚举/列表实现的包装器。它可能不会从存储的进程返回scaler结果集的字符串表示形式。我认为这条线应该更像:
Int32.TryParse(tEntities.ReadReviewCountByHotelId(hotelId).ToString(),out reviewCount);
因此很明显,这种情况下不存在任何记录。
r.Review\u HotelId=@HotelId
尝试提供一个不同的@HotelId
,该记录已存在于Review\u HotelId
列int32.TryParse(tEntities.ReadReviewCountByHotelId(HotelId.FirstOrDefault().ToString(),out reviewCount));在上面的修改之后它工作了,但是First或default应该返回一个null。应该没有理由将其转换为字符串并返回int。
reviewCount = tEntities.ReadReviewCountByHotelId(hotelId).First().Value