0

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.

VansFannel
  • 45,055
  • 107
  • 359
  • 626

1 Answers1

1

do you know another fastest method to check if that user exists

As you are using EF, you should be able to do this:

var user = context.Users.Find(userId)

if (user != null)
{
    //exists!
}

If that method is not available - this will do the same:

var user = context.Users.FirstOrDefault(u => u.UserId == userId);

if (user != null)
{
    //exists!
}

I suggest you also read the question: Update Row if it Exists Else Insert Logic with Entity Framework.

Community
  • 1
  • 1
dav_i
  • 27,509
  • 17
  • 104
  • 136