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 : 1173
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 : 1127
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.