通过调用datalayer将数据获取到ViewModel中
本文关键字:ViewModel 数据获取 调用 datalayer | 更新日期: 2023-09-27 18:19:26
我试图将存储的数据从SQLite数据库中获取到一个简单的文本框中,但一直为null。当数据层被调用时,数据一开始加载正确,但在某个时候它再次变为空,我不知道它在哪里或为什么出错。
这是我的ViewModel
public class FirstReadViewModel : NotifyUIBase
{
private string _scriptNotes;
public string ScriptNotes //binded in the View
{
get { return _scriptNotes; }
set { _scriptNotes = value; RaisePropertyChanged("ScriptNotes"); }
}
public FirstReadViewModel()
{
var dbFunctions = new DataLayer();
dbFunctions.GetFirstReadNotes();
}
}
DataLayer
public void GetFirstReadNotes()
{
String dbConnectionString = @"Data Source =DB.sqlite";
SQLiteConnection cnn = new SQLiteConnection(dbConnectionString);
cnn.Open();
SQLiteCommand cmd = new SQLiteCommand(cnn);
cmd.CommandText = "SELECT* FROM projects WHERE projectID = 1";
SQLiteDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string ScriptNotes = reader["scriptnotes"].ToString();
}
reader.Close();
cnn.Close();
}
}
您的数据层方法应该如下所示,因为您只想返回第一个音符:
public string GetFirstReadNotes()
{
string scriptNotes = string.Empty;
String dbConnectionString = @"Data Source =DB.sqlite";
SQLiteConnection cnn = new SQLiteConnection(dbConnectionString);
cnn.Open();
SQLiteCommand cmd = new SQLiteCommand(cnn);
cmd.CommandText = "SELECT* FROM projects WHERE projectID = 1";
SQLiteDataReader reader = cmd.ExecuteReader();
if(reader.Read())
{
scriptNotes = reader["scriptnotes"].ToString();
}
reader.Close();
cnn.Close();
}
return scriptNotes;
}
和FirstReadViewModel
如下:
public FirstReadViewModel()
{
var dbFunctions = new DataLayer();
this.ScriptNotes = dbFunctions.GetFirstReadNotes();
}
您应该使用接口将DataLayer
注入到FirstReadViewModel
中,并稍微更改代码
创建一个接口
interface IFirstReadViewModelDAL
{
string GetFirstReadNotes();
}
使用它,还可以使用的使用功能
internal class DataLayer: IFirstReadViewModelDAL
{
public string GetFirstReadNotes()
{
string ScriptNotes;
String dbConnectionString = @"Data Source =DB.sqlite";
using(SQLiteConnection cnn = new SQLiteConnection(dbConnectionString))
{
cnn.Open();
SQLiteCommand cmd = new SQLiteCommand(cnn);
cmd.CommandText = "SELECT* FROM projects WHERE projectID = 1";
using (SQLiteDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
ScriptNotes = reader["scriptnotes"].ToString();
}
}
}
return ScriptNotes;
}
}
使用接口注入DataLayer
private IFirstReadViewModelDAL dbFunctions;
private string _scriptNotes;
public string ScriptNotes //binded in the View
{
get { return _scriptNotes; }
set { _scriptNotes = value; RaisePropertyChanged("ScriptNotes"); }
}
public FirstReadViewModel(IFirstReadViewModelDAL injectDAL)
{
dbFunctions = injectDAL;
}
private void LoadData();
{
// use your dbFunctions
}
要注入它,你需要一个单独的类,比如
public class Controller
{
public static FirstReadViewModel getNewFirstReadViewModel()
{
var dal = new DataLayer();
var vm = new FirstReadViewModel(dal);
return vm;
}
}