Problème de migration base sqlite + c# + UWP
Bonjour,
Visual Studio 2017 Version 15.2 (26430.15) Release
Microsoft.EntityFrameworkCore.Sqlite V1.1.2
Microsoft.EntityFrameworkCore.Tools v1.1.1
Microsoft.NetCore.UniversalWindosPlatform v5.3.3
SQLite.Net-PCL v3.1.1
System.Data.SQLite v1.0.105.2
Microsoft .NET Framework 4.7.02046
Je débute dans l'utilisation de SQLIte via Entity Framework pour UWP.
Mon problème est le suivant: impossible de migrer ma base SQLite créée.
Dans la console:
Code:
1 2 3 4 5
|
PM> add-migration
applet de commande Add-Migration à la position 1 du pipeline de la commande
Fournissez des valeurs pour les paramètres suivants*:
Name: |
Je ne sait quoi mettre comme 'Name'???
De plus si j’exécute mon appli (qui en est à un stade plus que minimaliste), j'ai l'erreur suivante:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
L'exception Microsoft.EntityFrameworkCore.DbUpdateException s'est produite
HResult=0x80131500
Message=An error occurred while updating the entries. See the inner exception for details.
Source=<Impossible d'évaluer la source de l'exception>
Arborescence des appels de procédure*:
à Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection)
à Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(Tuple`2 parameters)
à Microsoft.EntityFrameworkCore.Storage.Internal.NoopExecutionStrategy.Execute[TState,TResult](Func`2 operation, Func`2 verifySucceeded, TState state)
à Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, Func`2 operation, TState state)
à Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(IEnumerable`1 commandBatches, IRelationalConnection connection)
à Microsoft.EntityFrameworkCore.Storage.RelationalDatabase.SaveChanges(IReadOnlyList`1 entries)
à Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(IReadOnlyList`1 entriesToSave)
à Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess)
à Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)
à Microsoft.EntityFrameworkCore.DbContext.SaveChanges()
à SQLiteUWPEF.MainPage..ctor() dans C:\Users\zest\documents\visual studio 2017\Projects\SQLiteUWPEF\SQLiteUWPEF\MainPage.xaml.cs :ligne 33
à SQLiteUWPEF.SQLiteUWPEF_XamlTypeInfo.XamlTypeInfoProvider.Activate_0_MainPage() dans C:\Users\Stéphane\documents\visual studio 2017\Projects\SQLiteUWPEF\SQLiteUWPEF\obj\x86\Debug\XamlTypeInfo.g.cs :ligne 178
à SQLiteUWPEF.SQLiteUWPEF_XamlTypeInfo.XamlUserType.ActivateInstance() dans C:\Users\Stéphane\documents\visual studio 2017\Projects\SQLiteUWPEF\SQLiteUWPEF\obj\x86\Debug\XamlTypeInfo.g.cs :ligne 333
Exception interne 1*:
SqliteException*: SQLite Error 1: 'table MyTable has no column named OneColumn'. |
Après mes recherche sur le Net, il s'agirais à priori d'un problème de migration de ma base.
Et là je n'y pige pas grand chose....donc: HELP!!
À vrai, dire je ne suis absolument pas certain de l'implémentation de mon code.
Merci
Mon MainPage.xaml.cs
Code:
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 Microsoft.EntityFrameworkCore;
using Windows.UI.Xaml.Controls;
using Windows.UI.Popups;
using System.Collections.Generic;
using System.Linq;
// Pour plus d'informations sur le modèle d'élément Page vierge, consultez la page https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace SQLiteUWPEF
{
/// <summary>
/// Une page vide peut être utilisée seule ou constituer une page de destination au sein d'un frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
List<string> outSQL = new List<string>();
using (var db = new MyContext())
{
//db.Database.EnsureCreated();
db.MyTable.Count();
MyEntity Stak = new MyEntity();
Stak.MyColumn = "ALBERT";
Stak.YourColumn = "Londres";
Stak.OneColumn = "AZERTY";
db.MyTable.Add(Stak);
db.SaveChanges();
outSQL = (from g in db.MyTable select g.MyColumn).ToList();
lstV1.ItemsSource = outSQL;
db.Dispose();
}
}
}
} |
MyContext.cs
Code:
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
|
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SQLiteUWPEF
{
public class MyContext : DbContext
{
// This property defines the table
public DbSet<MyEntity> MyTable { get; set; }
// This method connects the context with the database
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var connectionStringBuilder = new SqliteConnectionStringBuilder { DataSource = "uwp.sqlite" };
var connectionString = connectionStringBuilder.ToString();
var connection = new SqliteConnection(connectionString);
optionsBuilder.UseSqlite(connection);
}
}
} |
App.xaml.cs:
Code:
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 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
|
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Popups;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore.Migrations;
using System.IO;
using System.Runtime.InteropServices.WindowsRuntime;
namespace SQLiteUWPEF
{
/// <summary>
/// Fournit un comportement spécifique à l'application afin de compléter la classe Application par défaut.
/// </summary>
sealed partial class App : Application
{
/// <summary>
/// Initialise l'objet d'application de singleton. Il s'agit de la première ligne du code créé
/// à être exécutée. Elle correspond donc à l'équivalent logique de main() ou WinMain().
/// </summary>
public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending;
using (var db = new MyContext())
{
db.Database.Migrate();
}
//List<string> outSQL = new List<string>();
// using (var db = new MyContext())
// {
// db.Database.EnsureCreated();
// //db.Database.ApplyMigrations();
// //db.MyTable.migrate();
// //MyTable.Initialize(db);
// MyEntity Stak = new MyEntity();
// Stak.MyColumn = "ALBERT";
// //Stak.YourColumn = "Londres";
// //Stak.OneColumn = "AZERTY";
// db.MyTable.Add(Stak);
// db.SaveChanges();
// outSQL = (from g in db.MyTable select g.MyColumn).ToList();
// db.Dispose();
// var messageDialog = new MessageDialog(outSQL[1]);
// //foreach (string item in outSQL)
// //{
// // //displayNoWifiDialog(item);
// // var messageDialog = new MessageDialog(item);
// //}
// }
}
/// <summary>
/// Invoqué lorsque l'application est lancée normalement par l'utilisateur final. D'autres points d'entrée
/// seront utilisés par exemple au moment du lancement de l'application pour l'ouverture d'un fichier spécifique.
/// </summary>
/// <param name="e">Détails concernant la requête et le processus de lancement.</param>
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
Frame rootFrame = Window.Current.Content as Frame;
// Ne répétez pas l'initialisation de l'application lorsque la fenêtre comporte déjà du contenu,
// assurez-vous juste que la fenêtre est active
if (rootFrame == null)
{
// Créez un Frame utilisable comme contexte de navigation et naviguez jusqu'à la première page
rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
//TODO: chargez l'état de l'application précédemment suspendue
}
// Placez le frame dans la fenêtre active
Window.Current.Content = rootFrame;
}
if (e.PrelaunchActivated == false)
{
if (rootFrame.Content == null)
{
// Quand la pile de navigation n'est pas restaurée, accédez à la première page,
// puis configurez la nouvelle page en transmettant les informations requises en tant que
// paramètre
rootFrame.Navigate(typeof(MainPage), e.Arguments);
}
// Vérifiez que la fenêtre actuelle est active
Window.Current.Activate();
}
}
/// <summary>
/// Appelé lorsque la navigation vers une page donnée échoue
/// </summary>
/// <param name="sender">Frame à l'origine de l'échec de navigation.</param>
/// <param name="e">Détails relatifs à l'échec de navigation</param>
void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
{
throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
}
/// <summary>
/// Appelé lorsque l'exécution de l'application est suspendue. L'état de l'application est enregistré
/// sans savoir si l'application pourra se fermer ou reprendre sans endommager
/// le contenu de la mémoire.
/// </summary>
/// <param name="sender">Source de la requête de suspension.</param>
/// <param name="e">Détails de la requête de suspension.</param>
private void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
//TODO: enregistrez l'état de l'application et arrêtez toute activité en arrière-plan
deferral.Complete();
}
}
} |
MyEntity.cs
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using SQLite.Net.Attributes;
namespace SQLiteUWPEF
{
public class MyEntity
{
[PrimaryKey, AutoIncrement]
public int id { get; set; }
public string MyColumn { get; set; }
public string YourColumn { get; set; }
public string OneColumn { get; set; }
public MyEntity()
{
}
}
} |
MainPage.xaml
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
<Page
x:Class="SQLiteUWPEF.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:SQLiteUWPEF"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<TextBox x:Name="txtBox01" HorizontalAlignment="Left" Margin="112,114,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="138"/>
<ListView x:Name="lstV1" HorizontalAlignment="Left" Height="147" Margin="112,151,0,0" VerticalAlignment="Top" Width="238"/>
</Grid>
</Page> |