Ich möchte den ersten Datensatz aus der AboutUs-Tabelle abrufen und als Inhaltslabel anzeigen.Das Objekt wird nicht in der ViewModel-Klasse festgelegt, und die Steuerung wechselt direkt von der Datenzugriffsklasse zu View
Ich habe 4 Klassen in MVVM-Muster erstellt.
Zuerst ist das Modell Klasse AboutUs.cs
[Table("tblAboutUs")] public class AboutUs { [PrimaryKey, AutoIncrement, NotNull] public int IDP { get; set; } public string Content { get; set; } }
Zweitens ist Data Access Klasse
SQLiteAboutUs.cs
public class SQLiteAboutUs { private static readonly AsyncLock Mutex = new AsyncLock(); private SQLiteAsyncConnection dbConn; public int StatusCode { get; set; } public SQLiteAboutUs(ISQLitePlatform sqlitePlatform, string dbPath) { if (dbConn == null) { var connectionFunc = new Func<SQLiteConnectionWithLock>(() => new SQLiteConnectionWithLock ( sqlitePlatform, new SQLiteConnectionString(dbPath, storeDateTimeAsTicks: false) )); dbConn = new SQLiteAsyncConnection(connectionFunc); dbConn.CreateTableAsync<Model.AboutUs>(); } } public SQLiteAboutUs() { } public async Task Save(Model.AboutUs content) { using (await Mutex.LockAsync().ConfigureAwait(false)) { StatusCode = 0; await dbConn.InsertAsync(new Model.AboutUs { Content = content.Content }); StatusCode = 1; } //For Get first Row from Table public async Task<Model.AboutUs> GetAllData() { return await dbConn.Table<Model.AboutUs>().Where(x => x.IDP == 1).FirstOrDefaultAsync(); } }
Dritte Klasse Viewmodel Klasse
AboutUsViewModel.cs
public class AboutUsViewModel { readonly SQLiteAboutUs _db; public string AboutUsContent { get; set; } //public string AboutUs; public AboutUsViewModel() { _db = new SQLiteAboutUs(); } public async void FirstRecord() { Model.AboutUs obj = await _db.GetAllData(); this.AboutUsContent = obj.Content; } }
Forth ist-Code hinter Datei meiner XAML-Seiten.
AboutUs.xaml.cs
public partial class AboutUs : ContentPage { readonly AboutUsViewModel aboutUsViewModel; public AboutUs() { InitializeComponent(); aboutUsViewModel = new AboutUsViewModel(); aboutUsViewModel.FirstRecord(); lblContent.Text = aboutUsViewModel.AboutUsContent; } }
ich Debug-Code haben, aber Problem ist in AboutUsViewModel.cs Klasse in Firstrecord Method-Objekt kann auch nicht eingestellt wird, eingestellt werden, deshalb AboutUsContent String-Eigenschaft nicht .
Ich kann nicht herausfinden, warum mein Debugger direkt von GetAllData() -Methode in SQLiteAboutUs.cs zu label.text in Code hinter Datei der Ansicht springt?
Was genau ist hier null? Sind Sie sicher, dass dbConn nicht null ist? Es ist mir oft passiert. Kannst du auch versuchen, eine Variable wie diese zuzuweisen? var result = erwartet dbConn.Table(). Wobei (x => x.IDP == 1) .FirstOrDefaultAsync(); mit einem Versuch fangen vielleicht, nur um sicherzustellen, wenn FirstOrDefaultAsync das Problem macht oder Rückgabetyp macht das Problem? –
batmaci