简体   繁体   中英

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??

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM