IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Entity Framework Discussion :

ApplicationDBContext dans modeles ? [Débutant]


Sujet :

Entity Framework

  1. #1
    Membre éclairé Avatar de Nadinette
    Femme Profil pro
    Développeur Web
    Inscrit en
    Octobre 2012
    Messages
    264
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : France, Alpes Maritimes (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Développeur Web
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Octobre 2012
    Messages : 264
    Par défaut ApplicationDBContext dans modeles ?
    Bonjour,

    J'ai trouvé un exemple pour codefirster les tables de ASP.net.idendity dans un schéma spécifique.
    http://www.captechconsulting.com/blo...nt-API--Part-1
    Dans cet exemple, le fichier IdentityModels.cs regroupe plusieurs classes dont ApplicationDBContext.

    Dans me petite tête, il me semblait qu'il était déconseillé de mettre du code actif dans un modèle et qu'il devait être dans un contrôleur.

    J'aimerai avoir votre avis.

    Le code en question ne devrai-il pas être en dehors du namespace modèle ?

    Merci

  2. #2
    Modérateur
    Avatar de DotNetMatt
    Homme Profil pro
    CTO
    Inscrit en
    Février 2010
    Messages
    3 611
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 37
    Localisation : Etats-Unis

    Informations professionnelles :
    Activité : CTO
    Secteur : Finance

    Informations forums :
    Inscription : Février 2010
    Messages : 3 611
    Billets dans le blog
    3
    Par défaut
    Ce cas est particulier...

    Pour faire simple, oui ca peut être un Model, car après tout il s'agit bien de communiquer avec la base de données pour récupérer les infos de l'utilisateur.
    Autre point, ASP.NET Identity a besoin de System.Web et d'EntityFramework.

    Donc si tu as une architecture n-tiers et que par exemple tu veux isoler ca dans ta couche d'accès aux données, tu vas devoir ajouter une référence à System.Web dans cette couche, ce qui n'est pas souhaité....
    Less Is More
    Pensez à utiliser les boutons , et les balises code
    Desole pour l'absence d'accents, clavier US oblige
    Celui qui pense qu'un professionnel coute cher n'a aucune idee de ce que peut lui couter un incompetent.

  3. #3
    Membre éclairé Avatar de Nadinette
    Femme Profil pro
    Développeur Web
    Inscrit en
    Octobre 2012
    Messages
    264
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : France, Alpes Maritimes (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Développeur Web
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Octobre 2012
    Messages : 264
    Par défaut
    J'ai un peu avancé... J'arrive à créer la base avec les tables d'Identity et les miennes. Maintenant, je butte sur la migration.
    J'ai lu cet article : http://rdonfack.developpez.com/tutor...st-migrations/

    J'ai essayé d’exécuter le enable migration dans ma dll de dbcontext mais j'ai un message d'erreur :



    Each package is licensed to you by its owner. NuGet is not responsible for, nor does it grant any licenses to, third-party packages. Some packages may include dependencies which are governed by additional licenses. Follow the package source (feed) URL to determine any dependencies.

    Package Manager Console Host Version 3.3.0.167

    Type 'get-help NuGet' to see all available NuGet commands.



    Voici ma classe ApplicationDBContext

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
     
    using Layers.Data.Entities.Implementation.Business;
    using Layers.Data.Entities.Implementation.Security;
    using Microsoft.AspNet.Identity.EntityFramework;
    using System;
    using System.Collections.Generic;
    using System.Data.Entity;
    using System.Data.Entity.ModelConfiguration;
    using System.Data.Entity.ModelConfiguration.Conventions;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
     
    namespace Layers.Data.Context.Implementation
    {
        /// <summary>
        /// http://stackoverflow.com/questions/28531201/entitytype-identityuserlogin-has-no-key-defined-define-the-key-for-this-entit
        /// </summary>
        [DbConfigurationType(typeof(NpgsqlConfiguration))]
        public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
        {
            public ApplicationDbContext() : base("DefaultConnection")
            {
                Database.SetInitializer<ApplicationDbContext>(new CreateDatabaseIfNotExists<ApplicationDbContext>());
            }
            public DbSet<Genre> Genres { get; set; }
            public DbSet<Contact> Contacts { get; set; }
            public DbSet<Offer> Offers { get; set; }
            public DbSet<Media> Medias { get; set; }
            protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                modelBuilder.HasDefaultSchema("public");
                modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
                modelBuilder.Entity<Genre>().ToTable("Genres");
                modelBuilder.Entity<Contact>().ToTable("Contacts");
                modelBuilder.Entity<Media>().ToTable("Medias");
                modelBuilder.Entity<Offer>().ToTable("Offers");
                modelBuilder.Entity<Genre>().ToTable("Genres");
                modelBuilder.Configurations.Add(new IdentityUserLoginConfiguration());
                modelBuilder.Configurations.Add(new IdentityUserRoleConfiguration());
                base.OnModelCreating(modelBuilder);
            }
            public static ApplicationDbContext Create()
            {
                return new ApplicationDbContext();
            }
     
            public class IdentityUserLoginConfiguration : EntityTypeConfiguration<IdentityUserLogin>
            {
     
                public IdentityUserLoginConfiguration()
                {
                    HasKey(iul => iul.UserId);
                }
     
            }
     
            public class IdentityUserRoleConfiguration : EntityTypeConfiguration<IdentityUserRole>
            {
     
                public IdentityUserRoleConfiguration()
                {
                    HasKey(iur => iur.RoleId);
                }
     
            }
        }
    }
    Voici ma classe configuration

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
     
    using Layers.Common.Implementation;
    using Layers.Data.Entities.Implementation.Business;
    using Layers.Data.Entities.Implementation.Security;
    using Microsoft.AspNet.Identity;
    using Microsoft.AspNet.Identity.EntityFramework;
    using System;
    using System.Collections.Generic;
    using System.Data.Entity.Migrations;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
     
    namespace Layers.Data.Context.Implementation
    {
        public sealed class Configuration : DbMigrationsConfiguration<ApplicationDbContext>
        {
            public Configuration()
            {
                base.AutomaticMigrationsEnabled = true;
            }
            protected override void Seed(ApplicationDbContext dbContext)
            {
     
                IList<Genre> defaultGenres = new List<Genre>();
                defaultGenres.Add(new Genre() { Id = 1, Tag = "EtyGenreMr" });
                defaultGenres.Add(new Genre() { Id = 1, Tag = "EtyGenreMrs" });
                defaultGenres.Add(new Genre() { Id = 1, Tag = "EtyGenreMs" });
     
                dbContext.Genres.AddRange(defaultGenres);
     
                var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
                var user = new ApplicationUser()
                {
                    UserName = CommonEnvironment.AdminLogin,
                    Email = CommonEnvironment.AdminEMail,
                    PasswordHash = manager.PasswordHasher.HashPassword(CommonEnvironment.AdminPassword),
                    Contact = new Contact()
                    {
                        Genre = defaultGenres.Where(g => g.Id == CommonEnvironment.AdminGenreId).Single(),
                        FirstName = CommonEnvironment.AdminFirstName,
                        LastName = CommonEnvironment.AdminLastName
                    }
                };
                base.Seed(dbContext);
            }
        }
    }
    Si je désactive Automatic Migration, j'ai le message d'erreur :



    An exception of type 'System.Data.Entity.Migrations.Infrastructure.AutomaticMigrationsDisabledException' occurred in EntityFramework.dll but was not handled in user code



    Se le le laisse à trure, je ne passe jamais pas seed.

    Je ne comprends plus rien...

    Tu pourrais m'expliquer ?

    Merci

  4. #4
    Membre éclairé Avatar de Nadinette
    Femme Profil pro
    Développeur Web
    Inscrit en
    Octobre 2012
    Messages
    264
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : France, Alpes Maritimes (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Développeur Web
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Octobre 2012
    Messages : 264
    Par défaut J'ai trouvé !
    Salut,

    En fait il faut faire comme suit :

    Il faut une classe DB Initializer :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
     
        public class ApplicationDBInitializer : CreateDatabaseIfNotExists<ApplicationDbContext>
        {
            protected override void Seed(ApplicationDbContext dbContext)
            {
                IList<Genre> defaultGenres = new List<Genre>();
                defaultGenres.Add(new Genre() { Id = 1, Tag = "M" });
                defaultGenres.Add(new Genre() { Id = 2, Tag = "MME" });
                defaultGenres.Add(new Genre() { Id = 3, Tag = "MLE" });
     
                dbContext.Genres.AddRange(defaultGenres);
     
                var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
                var user = new ApplicationUser()
                {
                    UserName = Env.AdminLogin,
                    Email = Env.AdminEMail,
                    PasswordHash = manager.PasswordHasher.HashPassword(Env.AdminPassword),
                    Contact = new Contact()
                    {
                        Genre = defaultGenres.Where(g => g.Id == Env.AdminGenreId).Single(),
                        FirstName = Env.AdminFirstName,
                        LastName = Env.AdminLastName
                    }
                };
                base.Seed(dbContext);
            }
        }
    ensuite une classe ApplicatioDBContext :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
     
        public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
        {
            public ApplicationDbContext() : base("DefaultConnection")
            {
                Database.SetInitializer<ApplicationDbContext>(new ApplicationDBInitializer());
            }
            public DbSet<Genre> Genres { get; set; }
            public DbSet<Contact> Contacts { get; set; }
     
            protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                modelBuilder.HasDefaultSchema("public");//Pour postgr
                modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
                modelBuilder.Entity<Genre>().ToTable("Genres");
                modelBuilder.Entity<Contact>().ToTable("Contacts");
                modelBuilder.Configurations.Add(new IdentityUserLoginConfiguration());
                modelBuilder.Configurations.Add(new IdentityUserRoleConfiguration());
                base.OnModelCreating(modelBuilder);
            }
     
            public static ApplicationDbContext Create()
            {
                return new ApplicationDbContext();
            }
     
            public class IdentityUserLoginConfiguration : EntityTypeConfiguration<IdentityUserLogin>
            {
     
                public IdentityUserLoginConfiguration()
                {
                    HasKey(iul => iul.UserId);
                }
     
            }
     
            public class IdentityUserRoleConfiguration : EntityTypeConfiguration<IdentityUserRole>
            {
     
                public IdentityUserRoleConfiguration()
                {
                    HasKey(iur => iur.RoleId);
                }
     
            }
        }
    Et hop !

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Requete dans model
    Par nico_1 dans le forum MkFramework
    Réponses: 2
    Dernier message: 13/11/2013, 10h08
  2. [1.x] surcharger save dans model ou form?
    Par floringg dans le forum Symfony
    Réponses: 2
    Dernier message: 13/07/2012, 10h28
  3. [WD-2007] en tête/pieds de page -- controle du contenu dans modele
    Par Morgann Noémie dans le forum Word
    Réponses: 8
    Dernier message: 28/07/2010, 09h40
  4. [Zend_Db] MVC: Une classe métier dans "Model"
    Par salmoucha dans le forum Zend_Db
    Réponses: 7
    Dernier message: 04/04/2008, 09h57
  5. sous-repertoires dans models et controllers sous Rails
    Par bab_dev dans le forum Ruby on Rails
    Réponses: 1
    Dernier message: 03/12/2007, 14h43

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo