sql >> Base de Datos >  >> RDS >> Mysql

Relación de uno a muchos entre AspNetUsers (Identidad) y una tabla personalizada

He hecho exactamente esto en varios proyectos

Por ejemplo, tengo una relación de uno a muchos de ASPNetUsers a Notificaciones. Entonces, en mi clase ApplicationUser dentro de IdentityModels.cs tengo

public virtual ICollection<Notification> Notifications { get; set; }

Mi clase de Notificaciones tiene el reverso

public virtual ApplicationUser ApplicationUser { get; set; }

De forma predeterminada, EF creará una eliminación en cascada desde Notificación a AspNetUsers que no quiero, por lo que también tengo esto en mi clase Contexto

modelBuilder.Entity<Notification>()
    .HasRequired(n => n.ApplicationUser)
    .WithMany(a => a.Notifications)
    .HasForeignKey(n => n.ApplicationUserId)
    .WillCascadeOnDelete(false);

Solo recuerde que la definición de AspNetUSers se amplía en la clase ApplicationUser dentro de IdentityModels.cs que genera para usted el andamiaje de Visual Studios. Luego trátelo como cualquier otra clase/tabla en su aplicación

ACTUALIZACIÓN - aquí hay ejemplos de modelos completos

public class ApplicationUser : IdentityUser
{

    [StringLength(250, ErrorMessage = "About is limited to 250 characters in length.")]
    public string About { get; set; }

    [StringLength(250, ErrorMessage = "Name is limited to 250 characters in length.", MinimumLength=3)]
    public string Name { get; set; }

    public DateTime DateRegistered { get; set; }
    public string ImageUrl { get; set; }

    public virtual ICollection<Notification> Notifications { get; set; }

    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;
    }
}


public class Notification
{
    public int ID { get; set; }

    public int? CommentId { get; set; }

    public string ApplicationUserId { get; set; }

    public DateTime DateTime { get; set; }

    public bool Viewed { get; set; }

    public virtual ApplicationUser ApplicationUser { get; set; }

    public virtual Comment Comment { get; set; }

}