LINQ to Entities Update Query
I'm trying to do a simple update but I cannae for the life of me work out what I am doing wrong.
I have the following code which currently is not working - I'm getting not all code paths return a value.
public List<tblWeight> UpdateFeedback(string memberid, string locationid, int prikey, string feedback)
{
MyEntities updatefeedback = new MyEntities();
tblWeight newfeedback = (from q in updatefeedback.tblWeights
where q.MemberId == memberid &&
q.LocationId == locationid &&
q.PriKey == prikey
select q).SingleOrDefault();
updatefeedback.tblWeights.AddObject(newfeedback);
updatefeedback.SaveChanges();
}
Basically, I am attempting to update the Feedback column within tblWeight based upon the where clauses.
Can anyone开发者_如何转开发 point out where I am going wrong...drastically!!
- Sorry - the previous try/catch was legacy.
First off (for different reasons than your question), get rid of the block:
catch (Exception)
{
return null;
}
Second, you say that you return a List<tblWeight>
, but you aren't doing it anywhere in the function. You either need to return NULL inside the try block at the end, or, preferably, a properly populated List<tblWeight>
structure.
Either return the object you say you are going to return or change the function to return a "void" and return nothing.
As far as the exception handler goes, please read up a bit on best practices regarding handling exceptions. I won't reiterate it in this post, since it's been said many times before. I promise you that you'll write code faster, write less code, and write better code if you do.
Your UpdateFeedback
method is defined to return a List<tblWeight>
but when everything runs successfully (i.e. no exception is thrown) nothing is being returned which is a compilation error in C#.
I recommend that you get rid of the try/catch block altogether since catching and not rethrowing exceptions is very bad practice. If something goes wrong, you should get an exception to tell you why.
You then need to either return something that makes sense (e.g. return updatefeedback.tblWeights
) or change the method to have a void
return value (i.e don't return anything).
There's not a return within the try block or is that not what you're asking?
The error states that not all codepaths returns a value, which is true.
You only return a value (null) if you catch (and swallow) an exception. The normal (hopefully) path does not return anything.
You should either return something after SaveChanges or change the return value to void
精彩评论