Подтвердить что ты не робот

Свойство "Претензии" типа "AspNetUser" не является навигационным свойством

Я использую ASP.NET Identity 2.2. Я переношу старое членство ASP.NET в новую систему Identity. Я выполняю шаги, указанные в этой статье для выполнения миграции.

Я расширил IdentityUser и добавил еще несколько свойств, подобных следующим:

public partial class AspNetUser : IdentityUser
{
        public AspNetUser()
        {
            CreateDate = DateTime.Now;
            IsApproved = false;
            LastLoginDate = DateTime.Now;
            LastActivityDate = DateTime.Now;
            LastPasswordChangedDate = DateTime.Now;
            LastLockoutDate = DateTime.Parse("1/1/1754");
            FailedPasswordAnswerAttemptWindowStart = DateTime.Parse("1/1/1754");
            FailedPasswordAttemptWindowStart = DateTime.Parse("1/1/1754");
            Discriminator = "AspNetUser";
            LastModified = DateTime.Now;

            this.AspNetUserClaims = new HashSet<AspNetUserClaim>();
            this.AspNetUserLogins = new HashSet<AspNetUserLogin>();
            this.AspNetRoles = new HashSet<AspNetRole>();
        }
        ....
        public virtual Application Application { get; set; }
        public virtual ICollection<AspNetUserClaim> AspNetUserClaims { get; set; }
        public virtual ICollection<AspNetUserLogin> AspNetUserLogins { get; set; }
        public virtual ICollection<AspNetRole> AspNetRoles { get; set; }

}

В классе AspNetUser имеется несколько свойств, которые не включены для краткости.

Я могу успешно зарегистрировать пользователя с помощью системы идентификации:

 var manager = new ApplicationUserManager();
 var user = new AspNetUser
                {
                    UserName = UserName.Text.Trim(),
                    Email = Email.Text.Trim()
                };

 var result = manager.Create(user, Password.Text);

Но когда я ищу любого пользователя по адресу электронной почты/имени пользователя, я получаю исключение:

var existingUser = manager.FindByEmail(emailAddress);

Ошибка:

The property 'Claims' on type 'AspNetUser' is not a navigation property. 
The Reference and Collection methods can only be used with navigation properties. Use the Property or ComplexProperty method.

Обновление:

Если я удалю свойство AspNetUserClaims из класса AspNetUser, тогда я получаю список новых ошибок:

Schema specified is not valid. Errors: 
The relationship 'JanEntities.FK__AspNetU__Appli__628FA481' was not loaded because the type 'MyEntities.AspNetUser' is not available.
The following information may be useful in resolving the previous error:
The required property 'AspNetUserClaims' does not exist on the type 'SampleApp.Core.AspNetUser'.


The relationship 'MyEntities.AspNetUserRole' was not loaded because the type 'MyEntities.AspNetUser' is not available.
The following information may be useful in resolving the previous error:
The required property 'AspNetUserClaims' does not exist on the type 'SampleApp.Core.AspNetUser'.


The relationship 'MyEntities.FK_dbo_AspNetUserClaim_dbo_AspNetUser_User_Id' was not loaded because the type 'MyEntities.AspNetUser' is not available.
The following information may be useful in resolving the previous error:
The required property 'AspNetUserClaims' does not exist on the type 'SampleApp.Core.AspNetUser'.


The relationship 'MyEntities.FK_dbo_AspNetUserLogin_dbo_AspNetUser_UserId' was not loaded because the type 'MyEntities.AspNetUser' is not available.
The following information may be useful in resolving the previous error:
The required property 'AspNetUserClaims' does not exist on the type 'SampleApp.Core.AspNetUser'.

Ниже приведена диаграмма базы данных, которая содержит новые идентификационные таблицы ASP.NET: enter image description here

Может кто-нибудь помочь мне решить эту проблему? Любая помощь высоко ценится.

4b9b3361

Ответ 1

Здесь вы можете проверить свойства IdentityUser: https://msdn.microsoft.com/en-us/library/microsoft.aspnet.identity.entityframework.identityuser_properties(v=vs.108).aspx

Как вы можете видеть, такие свойства, как Claims, Logins, Roles, уже существуют. По умолчанию идентификатор asp.net использует DbContext, который наследует от IdentityDbContext https://msdn.microsoft.com/en-us/library/microsoft.aspnet.identity.entityframework.identitydbcontext%28v=vs.108%29.aspx

Этот класс настраивает многие вещи, такие как сопоставления таблиц и т.д. Можем ли мы увидеть ваш DbContext?

Итак, сначала попробуйте удалить добавленные ICollections и их инициализаторы из конструктора.