【发布时间】:2016-07-14 15:58:49
【问题描述】:
我有实体
public class User : BaseEntity, IEntity
{
public string UserName { get; set; }
public string Avatar { get; set; }
[IgnoreMap]
public string Password { get; set; }
public int RoleId { get; set; }
public virtual Role Role { get; set; }
public string RoleName { get; set; }
public int RangId { get; set; }
public string RangName { get; set; }
public string Email { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public string SurName { get; set; }
public DateTime? Birthday { get; set; }
public int Gender { get; set; }
public int? CountryId { get; set; }
public virtual Country Country { get; set; }
public int? CityId { get; set; }
public virtual City City { get; set; }
public string Skype { get; set; }
public string WebSite { get; set; }
public string Interest { get; set; }
public string Signature { get; set; }
public DateTime DateRegistered { get; set; }
public string IpAddress { get; set; }
public string PasswordChange { get; set; }
public Guid? ActivateKey { get; set; }
public DateTime? DatePasswordChange { get; set; }
public int TotalPost { get; set; }
public string NewEmail { get; set; }
我尝试更新用户角色
var user = this._userRepository.GetEntity(userId);
user.RoleId = role.Id;
我尝试将导航属性设置为 null
user.Role = null;
我尝试将导航属性设置为新角色
user.Role = role;
但我总是出错
附加信息:对数据库的更改已成功提交,但在更新对象上下文时出错。 ObjectContext 可能处于不一致的状态。内部异常消息:发生引用完整性约束冲突:关系一端的“Role.Id”的属性值与另一端的“User.RoleId”的属性值不匹配。
我正在使用的保存日期
this._context.Entry(entity).State = EntityState.Modified;
更新:
我发现了有趣的事实。有时我可以更改用户角色,有时我不能。 例子
当用户激活他的帐户时,我可以更改用户角色。
当用户更改电子邮件时,我无法更改用户角色。
我用的代码几乎一样
更新
激活用户的代码工作正常
public bool ActivateUser(Guid key)
{
var user = this._userRepository.GetEntity(item => item.ActivateKey == key);
var role = this._roleRepository.GetEntity(item => item.RoleType == RoleType.User);
if (user != null)
{
user.ActivateKey = null;
user.RoleId = role.Id;
this._userRepository.UpdateEntity(user);
this._userRepository.SaveChanges();
return true;
}
return false;
}
编辑电子邮件用户的代码,我收到错误
发生了参照完整性约束违规:属性 关系一端的“Role.Id”值与 另一端的“User.RoleId”的属性值。
public void UpdateEmail(int userId, string newEmail, string browserAgent, string ip)
{
var user = this._userRepository.GetEntity(item => item.Id == userId);
var role = this._roleRepository.GetEntity(item => item.RoleType == RoleType.NoActivation);
var activateKey = Guid.NewGuid();
var editEmailNotification = new EditEmailNotification
{
UserName = string.IsNullOrEmpty(user.FirstName) ? user.UserName : user.FirstName,
OldEmail = user.Email,
NewEmail = newEmail,
Ip = ip,
WebBrowseAgent = browserAgent,
ActivateKey = activateKey
};
user.NewEmail = newEmail;
user.ActivateKey = activateKey;
user.RoleId = role.Id;
this._userRepository.UpdateEntity(user);
this._userRepository.SaveChanges();
this.SendNotificationLetterChangedAccountEmail(editEmailNotification);
}
【问题讨论】:
-
我认为 BaseEntity 有一个带有属性 [Key] 的属性“Id”?
-
不,属性“Id”没有属性[Key]
-
这个一对多关系角色有 n 个用户吗?
标签: c# entity-framework entity-framework-6