Identity context w podejściu code first

Identity context w podejściu code first
DU
  • Rejestracja: dni
  • Ostatnio: dni
  • Postów: 143
0

Cześć,
Chcę Was zapytać o context w Identity. Robię sobie projekt w podejściu code first i chcę zrobić logowanie za pomocą Identity i teraz pytanie czy potrzebuję dwóch różnych kontekstów?
Zwykły DbContext do operacji crud'owych aplikacji, a do logowania IdentityDbContext? Czy mogę to wszystko zrobić w ramach jednego kontestu?
Model user'a wygląda tak public class User : IdentityUser więc czy to zwykły 'DbContext' czy też 'IdentityDbContext' wali takimi samymi błędami podczas migracji:
EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType.
EntityType 'IdentityUserRole' has no key defined. Define the key for this EntityType.
IdentityUserLogins: EntityType: EntitySet 'IdentityUserLogins' is based on type 'IdentityUserLogin' that has no keys defined. IdentityUserRoles: EntityType: EntitySet 'IdentityUserRoles' is based on type 'IdentityUserRole' that has no keys defined.

SZ
  • Rejestracja: dni
  • Ostatnio: dni
  • Postów: 1591
1

Od użytkowników masz klasę ApplicationUser która dziedziczy z IdentityUser. Myślę, że nie potrzebnie tworzysz klasę User.

DU
  • Rejestracja: dni
  • Ostatnio: dni
  • Postów: 143
0

No ale wydaje mi się, że mimo to powinna przejść migracja, czy mylę się?

SZ
  • Rejestracja: dni
  • Ostatnio: dni
  • Postów: 1591
0

Problem chyba leży w dbcontext. On powienien dziedziczyć z IdentityDbContext jak jest to domyślnie. I wtedy będzie widział klucze zdefiniowane w IdentityUser. Ale nie pokazałeś kodu to cieżko powiedzieć.

DU
  • Rejestracja: dni
  • Ostatnio: dni
  • Postów: 143
0

Model, id zakomentowane bo jeśli się nie mylę dziedziczy z IdentityUser

Kopiuj
public class User : IdentityUser
    {
        //public long Id { get; set; }
        public string LoginName { get; set; }
        public string Password { get; set; }
    }

Konteksty:

Kopiuj
public class AppDbLogin : IdentityDbContext<User>
    {
        public AppDbLogin() : base("DB")
        {
        }

        public DbSet<IdentityUserLogin> User { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }
    }
Kopiuj
public class AppDB : DbContext
    {
        public AppDB() : base ("DB")
        {
        }
        public DbSet<Employee> Employees { get; set; }
        public DbSet<StructCorporation> StructsCorporation { get; set; }
        
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        }
    }

Ogólnie zamysł był taki, że pierwszy kontekst maiłby służyć do logowania i wszystkich akcji związanych z autoryzacją itd. itp. natomiast drugi do całego cruda aplikacji, teraz jednak pomyślałem, że skoro i tak mi to nie wychodzi to lepiej jakbym miał jeden kontekst.

SZ
  • Rejestracja: dni
  • Ostatnio: dni
  • Postów: 1591
0

Ale zobacz jaki kontekst przekazujesz w migracji. Ale po co Ci dwa dbcontexty? ja to załatwiam jednym. Klasa Configuration.

DU
  • Rejestracja: dni
  • Ostatnio: dni
  • Postów: 143
0

Jak jest wszystko w jednym kontekście to wyskakuje błąd:
`One or more validation errors were detected during model generation:

Intranet.DAL.IdentityUserLogin: : EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType.
User: EntityType: EntitySet 'User' is based on type 'IdentityUserLogin' that has no keys defined.`

Kopiuj

public class AppDB : DbContext
    {
        public AppDB() : base ("DB")
        {
        }
        
        public DbSet<Employee> Employees { get; set; }
        public DbSet<StructCorporation> StructsCorporation { get; set; }
        public DbSet<IdentityUserLogin> User { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        }
    }
Kopiuj

internal sealed class Configuration : DbMigrationsConfiguration<AppDB>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }

        protected override void Seed(AppDB context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
            //  to avoid creating duplicate seed data.
        }
    }
SZ
  • Rejestracja: dni
  • Ostatnio: dni
  • Postów: 1591
0

A w dbset podaje się encje a ty masz jakieś identityuserlogin

DU
  • Rejestracja: dni
  • Ostatnio: dni
  • Postów: 143
0

Racja, tutaj to już zagrałem w zgaduj zgadule ale błędy nadal są.

Kopiuj
One or more validation errors were detected during model generation:

Intranet.DAL.IdentityUserRole: : EntityType 'IdentityUserRole' has no key defined. Define the key for this EntityType.
IdentityUserRoles: EntityType: EntitySet 'IdentityUserRoles' is based on type 'IdentityUserRole' that has no keys defined.
SZ
  • Rejestracja: dni
  • Ostatnio: dni
  • Postów: 1591
0

Powiem Ci tak: ja w DbContext nie mam ApplicationUser. Ale context musi dziedziczyć po IdentityDbContext generycznym.

DU
  • Rejestracja: dni
  • Ostatnio: dni
  • Postów: 143
0

Trochę urywkami odpowiadasz. Jeśli będę dziedziczył z IdentityDbContext to chyba nie będę mógł korzystać z innych tabel w bazie.

SZ
  • Rejestracja: dni
  • Ostatnio: dni
  • Postów: 1591
0

Wszystkie dbsety robisz w dbcontext który dziedziczy z IdentityDbcontext<User>
Mój dbContext tak wygląda

Kopiuj
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public DbSet<Gig> Gigs { get; set; }
        public DbSet<Genre> Genres { get; set; }
        public DbSet<Attendance> Attendances { get; set; }
        public DbSet<Following> Followings { get; set; }
        public DbSet<Notification> Notifications { get; set; }
        public DbSet<UserNotification> UserNotifications { get; set; }
        public ApplicationDbContext()
            : base("DefaultConnection", throwIfV1Schema: false)
        {
        }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder
                .Entity<Attendance>()
                .HasRequired(a => a.Gig)
                .WithMany(g=>g.Attendances)
                .WillCascadeOnDelete(false);

            modelBuilder.Entity<ApplicationUser>()
                .HasMany(u => u.Followers)
                .WithRequired(f => f.Followee)
                .WillCascadeOnDelete(false);

            modelBuilder.Entity<ApplicationUser>()
                .HasMany(u => u.Followees)
                .WithRequired(f => f.Follower)
                .WillCascadeOnDelete(false);

            modelBuilder.Entity<UserNotification>()
                .HasRequired(n => n.User)
                .WithMany(u=>u.UserNotifications)
                .WillCascadeOnDelete(false);

            base.OnModelCreating(modelBuilder);
        }
    }
DU
  • Rejestracja: dni
  • Ostatnio: dni
  • Postów: 143
0

Ok, mógłbyś jeszcze pokazać ApplicationUser? Jak rozwiązałeś takie błędy:
Intranet.DAL.IdentityUserRole: : EntityType 'IdentityUserRole' has no key defined. Define the key for this EntityType. Intranet.DAL.IdentityUserLogin: : EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType. IdentityUserRoles: EntityType: EntitySet 'IdentityUserRoles' is based on type 'IdentityUserRole' that has no keys defined. IdentityUserLogins: EntityType: EntitySet 'IdentityUserLogins' is based on type 'IdentityUserLogin' that has no keys defined.

SZ
  • Rejestracja: dni
  • Ostatnio: dni
  • Postów: 1591
0

Ja nie miałem takich błędów. Korzystałem z klasy ApplicationUser która jest wbudowana w ASP identity.
pokaż jeszcze Configuration cs.

Kopiuj
public class ApplicationUser : IdentityUser
    {
        [Required]
        [StringLength(100)]
        public string Name { get; set; }
        public ICollection<Following> Followers { get; set; }
        public ICollection<Following> Followees { get; set; }
        public ICollection<UserNotification> UserNotifications { get; set; }

        public ApplicationUser()
        {
            Followers = new Collection<Following>();
            Followees = new Collection<Following>();
            UserNotifications = new Collection<UserNotification>();
        }

        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }

       
    }
DU
  • Rejestracja: dni
  • Ostatnio: dni
  • Postów: 143
0

Już wszystko działa, dzięki :) wyczyściłem projekt, przebudowałem i chodzi.

Zarejestruj się i dołącz do największej społeczności programistów w Polsce.

Otrzymaj wsparcie, dziel się wiedzą i rozwijaj swoje umiejętności z najlepszymi.