0

我正在尝试首先更新 EF 代码中的实体。

单击按钮时我运行此代码

bool result
if (hasPrivilege == true)result = userManager.RemoveUserPrivilege(Username, privilege, out errors);
else result = userManager.GiveUserPrivilege(Username, privilege, out errors);

然后我检查该方法是否成功并更新我的权限列表以显示新值。

if (result == false) txtBlkErrorMessages.Text = string.Join("\n", errors);
else
{
       privilegeCache = privileges.GetAll(int.MaxValue).Where(prv => prv.Username == Username).OrderBy(prv => prv.PrivilegeName).ToList();
       DisplayInDataGid();
}

问题是第一部分成功更新了数据库(我已经设置了一个断点并对数据库运行查询。但是第二部分仍然检索以前的值。

例如,如果我选择一个为真的权限并单击按钮,它应该删除该权限,然后立即显示该权限为假,但它只是表明它是真的。

如果我关闭窗口然后再次打开它,值会显示新的。

我尝试将 privilgeCache 对象设置为 null 然后获取权限。没有喜悦。

实体类在这里:

public sealed class UserPrivilege
{
    /// <summary>
    /// PRIMARY KEY -> THE NAME OF THE USER
    /// MUST BE BETWEEN 5 and 30 CHARACTERS AND IS A REQUIRED FIELD
    /// </summary>
    [Key, Column(Order = 0), Required, StringLength(30, MinimumLength = 5), Display(Name = "Username")]
    public string Username { get; set; }

    /// <summary>
    /// PRIMARY KEY -> THE NAME OF THE PRIVILEGE
    /// MUST BE BETWEEN 5 and 30 CHARACTERS AND IS A REQUIRED FIELD
    /// </summary>
    [Key, Column(Order = 1), Required, StringLength(30, MinimumLength = 5), Display(Name = "Privilege Name")]
    public string PrivilegeName { get; set; }

    /// <summary>
    /// WHETHER THE USERNAME HOLDS THE PRIVILEGE OR NOT
    /// </summary>
    [Required, Display(Name = "Holds Privilege")]
    public bool HoldsPrivilege { get; set; } 

}

更新数据库的代码在这里:

        try
        {
            userPrivilegeRepository.UpdateUserPrivilege(username, privilege, hasPrivilege);

            logger.WriteLog(LogTitle.UserPrivilegeUpdated, LogLevels.Information, LogData);
            return true;
        }
        catch (Exception ex)
        {
            errors.Add(string.Format(ErrorMessages.ErrorOccured, "Updating a user privilege"));
            logger.WriteLog(LogTitle.ExceptionThrown, LogLevels.Critical, LogData, ex);
            return false;
        }

最后更新方法的存储库代码是:

public bool UpdateUserPrivilege(string username, string privilege, bool hasPrivilege)
{
    //GET THE ACCOUNT
    UserPrivilege acct = GetByKeys(new string[] { username, privilege });

    //IF AN ACCOUNT WAS FOUND
    if (acct != null)
    {
        //UPDATE THE FIELDS
        acct.HoldsPrivilege = hasPrivilege;
    }

    bool success = (Database.SaveChanges() > 0);

    //SAVE THE CHANGES
    return success;
}

我有一种感觉,这是两件事之一:

  1. EF 正在某处缓存该值,如果是,我该如何清除缓存?
  2. 前段时间我遇到了一个问题,EF 设计器是视觉工作室,其中实体的键弄乱了东西,但我看不出如何安全地更改该实体上的键。

我在用:

  • 视觉工作室 2013
  • C# 4.5
  • MYSQL数据库

我希望有人能帮帮忙!

4

0 回答 0