简体   繁体   中英

c# , Entity Framework Stored Procedure

I am using Entity Framework. I have the following:

var db = new LikEntities();

GetParamAlerts_Result paramRslt = db.GetParamAlerts();

GetParamAlerts is a stored procedure and it is of type

System.Data.Objects.ObjectResult<GetParamAlerts_Result>

Note the GetParamAlerts returns multiple rows.

When I run the code above I the following error message :

Cannot implicitly convert type:

'System.Data.Objects.ObjectResult' to 'PVT_Alert_Notification.GetParamAlerts_Result'

Not sure how to resolve this.

This is because Entity Framework cannot guarantee that your stored procedure will always return a single row, so it's put into a ObjectResult which is just an enumerable collection . If you're always expecting a single result, you can use db.GetParamAlerts().Single() to get the result as GetParamAlerts_Result , or use any of the standard enumerable methods like First() , FirstOrDefault() , SingleOrDefault() , etc.

it looks like you should either be using

PVT_Alert_Notification.GetParamAlerts_Result paramRslt = db.GetParamAlerts();

or the method is returning the wrong type? Can you pot the code for the method? or you are getting a collection ?

If you have a collection, you could use:

var result = db.GetParamAlerts();
return result.FirstOrDefault();

You will see a similar post here

try incorporating first or default at the end

 GetParamAlerts_Result paramRslt = db.GetParamAlerts().FirstOrDefault();

try using cast

  GetParamAlerts_Result paramRslt = db.GetParamAlerts().Cast<GetParamAlerts_Result>().ToList(); 

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