繁体   English   中英

更新数据库中不存在的用户

[英]Updating a user that doesn't exist on database

我正在开发使用Entity Framework CodeFirst的WCF REST服务。

我有此方法可以插入或更新用户:

    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;
    }

但是,当我尝试更新不在数据库中的用户时出现错误。

我想我可以先检查该用户是否存在以下代码:

var users = from u in context.Users
            where u.UserId == userId
            select u;

if ((users != null) &&
    (users.Count() == 1))
{
    user = users.First();

但是, 您知道另一种检查该用户是否存在的最快方法吗?

也许我可以使用context.Entry但是我对Entity Framework很新的。

您知道另一种最快的方法来检查该用户是否存在

在使用EF时,您应该能够执行以下操作:

var user = context.Users.Find(userId)

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

如果该方法不可用-将执行以下操作:

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

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

我建议您也阅读以下问题: 如果存在使用实体框架插入逻辑,请更新行

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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