Syed Mhamudul Hasan
Syed Mhamudul Hasan

Reputation: 1349

Return null value in EF6 query with sql server

I am using Sp to produce some logic and return a table object.If no object found i just simply return null of a entity

CREATE proc SpDealerDistributionOracle 
(
    @DealerCode varchar(50),
    @imei varchar(50)
) 
as
BEGIN
    if (some logic)
        select  top 1 * from tblBarCodeInv
    else 
        select null;
END

Works fine ..But when I wrote query in EF 6 like this

 tblBarCodeInv returnValue = null;
 using (var db=new RBSYNERGYEntities())
 {
       String query = String.Format("SpDealerDistributionOracle 'DealerCode','101001'");
       returnValue = db.Database.SqlQuery<tblBarCodeInv>(query).FirstOrDefault();                  
 }
 return returnValue;

It throws an exception.

I simply want to return a object if not found return null and do some logic in C#.Can anybody help??

Upvotes: 2

Views: 495

Answers (1)

Gilad Green
Gilad Green

Reputation: 37299

Change your procedure to still return a "collection" in both cases. However in the second case it will be an empty collection and thus will reach the "Default" of the FirstOrDefault

BEGIN    
    if (some logic)
        select  top 1 * from tblBarCodeInv
    else 
        SELECT TOP 0 * from tblBarCodeInv 
END

Upvotes: 2

Related Questions