【问题标题】:The override UserName string length did not work when calling UserManager.CreateUserAsync, even the db has the correct string length.调用 UserManager.CreateUserAsync 时,覆盖用户名字符串长度不起作用,即使数据库具有正确的字符串长度。
【发布时间】:2017-08-11 02:46:16
【问题描述】:

问题很简单,我将用户名属性的默认长度(32)修改为 500,但代码似乎卡在 32。知道为什么会发生这种情况吗?

AbpUsers 的用户名字符串长度:

public class User : AbpUser<User>
{
    [MaxLength(500)]
    public override string UserName { get; set; }
}

这已经成功更新了 db UserName 长度。

但是当我打电话时

CheckErrors(await UserManager.CreateAsync(user));

它会返回:

System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. 

困扰我的是SaveChanges无法捕捉到这种异常:

public override int SaveChanges()
    {
        try
        {
            return base.SaveChanges();
        }
        catch (DbEntityValidationException e)
        {
            foreach (var eve in e.EntityValidationErrors)
            {
                Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                    eve.Entry.Entity.GetType().Name, eve.Entry.State);
                foreach (var ve in eve.ValidationErrors)
                {
                    Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                        ve.PropertyName, ve.ErrorMessage);
                }
            }
            throw;
        }
   }

非常感谢您的帮助!

【问题讨论】:

    标签: ef-code-first aspnetboilerplate


    【解决方案1】:

    AbpUserBase 中有一个名为 MaxUserNameLength 的常量。所以基本上你需要改变那个常数值。

      [Table("AbpUsers")]
      public abstract class AbpUserBase : FullAuditedEntity<long>, IMayHaveTenant, IPassivable
        {
            /// <summary>
            /// Maximum length of the <see cref="UserName"/> property.
            /// </summary>
            public const int MaxUserNameLength = 500;
    
            //...
    }
    

    此修改背后的原因是 UserName 正在验证 UserDto 类,如下所示;

    [Required]
    [StringLength(AbpUserBase.MaxUserNameLength)]
    public string UserName { get; set; }
    

    【讨论】:

    • 对不起,我已经尝试覆盖 AbpUserBase 并在代码中引用新的 MaxUserNameLength,但仍然没有成功。
    • 你需要在base.OnModelCreating(modelBuilder)行之前在DbContext中做
    • 感谢您的回复,但请您帮忙解释一下如何修改 OnModelCreating 中的 MaxUserNameLength 吗?很抱歉,我不太明白为什么这很重要。我创建了一个新数据库,其中 UserName 注释明确设置为 [StringLength(1000)]。 EF 可以成功生成具有 nvarchar 1000 的表,但不知何故插入不起作用。
    • 因为 UserDto 类的 MaxLength 属性引用了 AbpUserBase.MaxUserNameLength
    • 我已删除 UserDto 属性并将其设置为 [StringLength(1000)]
    【解决方案2】:

    在与 abp 模板进行数小时比较后,我发现发生这种情况的原因是因为我使用 [MaxLength] 而不是 [StringLength] 作为用户实体。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-21
      • 2013-11-28
      • 1970-01-01
      • 1970-01-01
      • 2015-11-29
      • 2013-12-07
      • 2018-07-19
      • 1970-01-01
      相关资源
      最近更新 更多