4
I’m developing software in C# with MVVM model, and with Visual Studio.
It is a software to manage the members of a university.
We must also use a database, with Code First.
My problem is it gives me the following mistake:
"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 out 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" Model 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 model 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
extend in the superclass Person
, with other attributes.
Thanks, I’ll change the code, and then I’ll give you some feedback. I’m sorry for some stupid mistakes, because we are now learning to use c# and the teacher, does not explain how to explain and we are a little left to do in case of mistakes!
– ZelDias
If you have any more specific ones, I try to improve them.
– Maniero
thank you very much, I am doing step by step, with the indications you gave me, and I have put the result. Thank you :)
– ZelDias