I'm developing C # software with the MVVM template , and with Visual Studio.
It is software to manage the members of a university.
We also have to use a database with Code First.
My problem is that it gives me the following error:
"An exception of type 'System.NullReferenceException' occurred in UniversityMembers.exe but was not handled in user code Additional information: Object reference not set to an instance of an object. "
I'll point the error in the code below:
public partial class MainWindow : Window
{
private static VMUniversityMembers d = new VMUniversityMembers();
ProjectContext db = d.ProjectContext;
public MainWindow()
{
InitializeComponent();
using (db)
{
var query = (DataContext as VMUniversityMembers).ProjectContext.UniversityMembers.SqlQuery("Select * from UniversityMembers"); **<---- Dá o erro aqui**
foreach (var item in query)
{
listView.Items.Add(item);
}
}
}
}
"VM UniversityMembers" is the View Model between the "UniversityMembers" Template and the graphical interface:
namespace UniversityMembers.ViewModel
{
class VMUniversityMembers:BaseModel
{
private ProjectContext projectContext;
private UniversityMember selectedMember = null;
public List<UniversityMember> Members
{
get
{
return projectContext.UniversityMembers.Include("Position").Include("Sex").ToList();
}
}
public ProjectContext ProjectContext
{
get
{
return projectContext;
}
set
{
projectContext = value;
}
}
public UniversityMember SelectedMember
{
get
{
return selectedMember;
}
set
{
selectedMember = value;
}
}
/**
* Método para adicionar alunos
*/
internal void Add()
{
var unmbm = new UniversityMember();
projectContext.UniversityMembers.Add(unmbm);
this.selectedMember = unmbm;
this.OnPropertyChanged("UniversityMembers");
}
internal void Cancel()
{
}
/**
*Método para guardar a informacao introduzida
*
*/
internal void SaveContext()
{
projectContext.SaveChanges();
this.OnPropertyChanged("UniversityMembers");
}
/**
* Método para eliminar um utilizador seleccionado na lista
*
*/
internal void Delete()
{
projectContext.UniversityMembers.Remove(SelectedMember);
}
}
}
And the template I use is the UniversitYMembers:
namespace UniversityMembers.Models
{
class UniversityMember : Person
{
public string email;
// public Position position;
public string migration;
public string Email { get { return email; } set { email = value; } }
// public Position Position { get { return position; } set { position = value; } }
public UniversityMember()
{
}
}
}
The class UniversityMembers
extends in the superclass Person
, with other attributes.