我试图将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();
}
}
答案 0 :(得分:0)
您的数据层方法应如下所示,因为您只想返回第一个注释:
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();
}
答案 1 :(得分:0)
您应该使用界面在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;
}
}