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 :

Erreur création d'entité


Sujet :

Entity Framework

  1. #1
    Membre à l'essai
    Femme Profil pro
    Analyste d'exploitation
    Inscrit en
    Janvier 2018
    Messages
    14
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Arabie Saoudite

    Informations professionnelles :
    Activité : Analyste d'exploitation

    Informations forums :
    Inscription : Janvier 2018
    Messages : 14
    Points : 14
    Points
    14
    Par défaut Erreur création d'entité
    Bonsoir à tous,

    Je suis confronté à une erreur depuis plus de 2 jours, je vient alors solliciter l'aide de personne plus aguerries que moi en .NET / EF.

    J'ai créer une base de données en ADO.NET avec un modèle contenant 2 classes distinctes que voici :

    Nom : BDD.PNG
Affichages : 940
Taille : 13,3 Ko

    J'ai ensuite ajouter une connexion serveur avec un fichier nommé "data.mdf" stocké dans mon projet, comme on peut le voir dans mon arborescence :


    Nom : arbo.PNG
Affichages : 927
Taille : 5,4 Ko

    Je veut maintenant créer une instance de chaque classe (Person + Address) dans mon fichier "Program.cs", que voici :

    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
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Runtime.Remoting.Contexts;
    using System.Data.Entity.Infrastructure;
     
    namespace EF
    {
        class Program
        {
            static void Main(string[] args)
            {
                using (MyDatabaseContainer dbContext
                  = new MyDatabaseContainer())
                {
     
                    dbContext.Database.CreateIfNotExists();
                    dbContext.Persons.Add(new Person()
                    {
                        FirstName = "John",
                        LastName = "Doe",
                        RegistrationDate = DateTime.Now,
                        Address = new Address()
                        {
                            Number = 36,
                            Street = "Quai des Orfèvres",
                            ZipCode = 75001,
                            City = "Paris"
                        }
                    });
     
                    try
                    {
                        dbContext.SaveChanges();
                    }
                    catch (DbUpdateException Ex)
                    {
                        Console.WriteLine(Ex.InnerException);
                        Console.ReadLine();
                    }
                }
            }
        }
    }

    Le problème est qu'une erreur interne est levée pendant l'exécution du code pour créer les deux instances sur ma base de données ... :/



    J'ai réussi à capturer l'erreur : La pile qui explique que l'objet nommé 'dbo.Addresses' n'existe pas :

    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
    System.Data.Entity.Core.UpdateException: Une erreur s'est produite lors de la mise à jour des entrées. Pour plus d'informations, consultez l'exception interne. ---> System.Data.SqlClient.SqlException: Invalid object name 'dbo.Addresses'.
       à System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
       à System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
       à System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
       à System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
       à System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
       à System.Data.SqlClient.SqlDataReader.get_MetaData()
       à System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted)
       à System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
       à System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
       à System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
       à System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
       à System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
       à System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
       à System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<Reader>b__c(DbCommand t, DbCommandInterceptionContext`1 c)
       à System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
       à System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext)
       à System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior)
       à System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
       à System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(Dictionary`2 identifierValues, List`1 generatedValues)
       à System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
       --- Fin de la trace de la pile d'exception interne ---
       à System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
       à System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.<Update>b__2(UpdateTranslator ut)
       à System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update[T](T noChangesResult, Func`2 updateFunction)
       à System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update()
       à System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore>b__35()
       à System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
       à System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction)
       à System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass2a.<SaveChangesInternal>b__27()
       à System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
       à System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean executeInExistingTransaction)
       à System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions options)
       à System.Data.Entity.Internal.InternalContext.SaveChanges()

    Voici le contenu du mon fichier "Mydatabase.edmx.sql" :

    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
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    -- --------------------------------------------------
    -- Entity Designer DDL Script for SQL Server 2005, 2008, 2012 and Azure
    -- --------------------------------------------------
    -- Date Created: 01/03/2019 17:24:50
    -- Generated from EDMX file: C:\Users\Thibaut\source\repos\EF\EF\MyDatabase.edmx
    -- --------------------------------------------------
     
    SET QUOTED_IDENTIFIER OFF;
    GO
    USE [data];
    GO
    IF SCHEMA_ID(N'dbo') IS NULL EXECUTE(N'CREATE SCHEMA [dbo]');
    GO
     
    -- --------------------------------------------------
    -- Dropping existing FOREIGN KEY constraints
    -- --------------------------------------------------
     
     
    -- --------------------------------------------------
    -- Dropping existing tables
    -- --------------------------------------------------
     
     
    -- --------------------------------------------------
    -- Creating all tables
    -- --------------------------------------------------
     
    -- Creating table 'Persons'
    CREATE TABLE [dbo].[Persons] (
        [Id] int IDENTITY(1,1) NOT NULL,
        [FirstName] nvarchar(max)  NOT NULL,
        [LastName] nvarchar(max)  NOT NULL,
        [RegistrationDate] datetime  NOT NULL,
        [Address_Id] int  NOT NULL
    );
    GO
     
    -- Creating table 'Addresses'
    CREATE TABLE [dbo].[Addresses] (
        [Id] int IDENTITY(1,1) NOT NULL,
        [Number] int  NOT NULL,
        [Street] nvarchar(max)  NOT NULL,
        [City] nvarchar(max)  NOT NULL,
        [ZipCode] int  NOT NULL
    );
    GO
     
    -- --------------------------------------------------
    -- Creating all PRIMARY KEY constraints
    -- --------------------------------------------------
     
    -- Creating primary key on [Id] in table 'Persons'
    ALTER TABLE [dbo].[Persons]
    ADD CONSTRAINT [PK_Persons]
        PRIMARY KEY CLUSTERED ([Id] ASC);
    GO
     
    -- Creating primary key on [Id] in table 'Addresses'
    ALTER TABLE [dbo].[Addresses]
    ADD CONSTRAINT [PK_Addresses]
        PRIMARY KEY CLUSTERED ([Id] ASC);
    GO
     
    -- --------------------------------------------------
    -- Creating all FOREIGN KEY constraints
    -- --------------------------------------------------
     
    -- Creating foreign key on [Address_Id] in table 'Persons'
    ALTER TABLE [dbo].[Persons]
    ADD CONSTRAINT [FK_PersonAddress]
        FOREIGN KEY ([Address_Id])
        REFERENCES [dbo].[Addresses]
            ([Id])
        ON DELETE NO ACTION ON UPDATE NO ACTION;
    GO
     
    -- Creating non-clustered index for FOREIGN KEY 'FK_PersonAddress'
    CREATE INDEX [IX_FK_PersonAddress]
    ON [dbo].[Persons]
        ([Address_Id]);
    GO
     
    -- --------------------------------------------------
    -- Script has ended
    -- --------------------------------------------------

    Merci par avance de votre aide qui me serait précieuse pour avancer et mieux comprendre mon erreur.
    Thibaut.

  2. #2
    Expert confirmé
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Novembre 2009
    Messages
    2 025
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 34
    Localisation : France, Bouches du Rhône (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Développeur .NET

    Informations forums :
    Inscription : Novembre 2009
    Messages : 2 025
    Points : 5 462
    Points
    5 462
    Par défaut
    Probablement une mauvaise connection strig (ne pointe pas vers ton fichier mdf) dans app.config

  3. #3
    Membre du Club
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Novembre 2018
    Messages
    34
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 38
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur .NET
    Secteur : Finance

    Informations forums :
    Inscription : Novembre 2018
    Messages : 34
    Points : 47
    Points
    47
    Par défaut
    tu n'aurais pas déplacer le *.mdf d'un répertoire vers un autre? certaine fois ça pose problème. (vérifie les namespace)
    sinon, vérifier dans le code généré si il n'y a pas une incohérence.

Discussions similaires

  1. Erreur création d'une requete
    Par puppusse79 dans le forum Access
    Réponses: 1
    Dernier message: 18/05/2006, 23h50
  2. Erreur création dynamique de contrôle
    Par thierrybatlle dans le forum Access
    Réponses: 1
    Dernier message: 10/02/2006, 11h00
  3. [SOAP][Web Service] erreur création d'une référence Web
    Par Maximil ian dans le forum XML/XSL et SOAP
    Réponses: 6
    Dernier message: 20/06/2005, 13h29
  4. [Firebird - D7] Erreur - Création dynamique d'une base
    Par EGI dans le forum Bases de données
    Réponses: 5
    Dernier message: 29/03/2005, 14h26
  5. FOXPRO 2.6 : erreur créations du /des fichiers CAB
    Par breihtiti dans le forum Autres SGBD
    Réponses: 2
    Dernier message: 16/11/2002, 11h28

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