I'm developing a WCF REST service that uses Entity Framework CodeFirst.
I have this method to insert or update a user:
private User InsertOrUpdateUser(User user)
{
OutgoingWebResponseContext ctx =
WebOperationContext.Current.OutgoingResponse;
// Check if user parameter is null
ParameterCheck.CheckUser(user);
// If user.UserId is not set (its value is less than 1), we are
// creating a new user.
bool isPost = (user.UserId == 0);
// Check if user has all its required fields, filled
if (isPost)
ParameterCheck.CheckUserData(user);
try
{
using (var context = new AdnLineContext())
{
context.Entry(user).State = user.UserId == 0 ?
EntityState.Added :
EntityState.Modified;
context.SaveChanges();
// If is POST, we are creating a new resource
if (isPost)
ctx.SetStatusAsCreated(CreateUserUri(user));
else
ctx.StatusCode = System.Net.HttpStatusCode.OK;
}
}
catch (Exception ex)
{
ctx.StatusCode = System.Net.HttpStatusCode.InternalServerError;
ctx.SuppressEntityBody = true;
}
return user;
}
But I get an error when I'm trying to update a user that it isn't on database.
I think I can check first if that user exists with this code:
var users = from u in context.Users
where u.UserId == userId
select u;
if ((users != null) &&
(users.Count() == 1))
{
user = users.First();
But, do you know another fastest method to check if that user exists?
Maybe I can use context.Entry
but I'm very new on Entity Framework
.