wpf mvvm crud example

141

wpf mvvm crud example -

public class StudentRecord : ViewModelBase
{
	private int _id;
	public int Id
	{
		get
		{
			return _id;
		}
		set
		{
			_id = value;
			OnPropertyChanged("Id");
		}
	}

	private string _name;
	public string Name
	{
		get
		{
			return _name;
		}
		set
		{
			_name = value;
			OnPropertyChanged("Name");
		}
	}

	private int _age;
	public int Age
	{
		get
		{
			return _age;
		}
		set
		{
			_age = value;
			OnPropertyChanged("Age");
		}
	}

	private string _address;
	public string Address
	{
		get
		{
			return _address;
		}
		set
		{
			_address = value;
			OnPropertyChanged("Address");
		}
	}

	private string _contact;
	public string Contact
	{
		get
		{
			return _contact;
		}
		set
		{
			_contact = value;
			OnPropertyChanged("Contact");
		}
	}

	private ObservableCollection<StudentRecord> _studentRecords;
	public ObservableCollection<StudentRecord> StudentRecords
	{
		get
		{
			return _studentRecords;
		}
		set
		{
			_studentRecords = value;
			OnPropertyChanged("StudentRecords");
		}
	}

	private void StudentModels_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
	{
		OnPropertyChanged("StudentRecords");
	}
}

wpf mvvm crud example -

public class StudentRepository
{
	private StudentEntities studentContext = null;

	public StudentRepository()
	{
		studentContext = new StudentEntities();
	}

	public Student Get(int id)
	{
		return studentContext.Students.Find(id);
	}

	public List<Student> GetAll()
	{
		return studentContext.Students.ToList();
	}

	public void AddStudent(Student student)
	{
		if (student != null)
		{
			studentContext.Students.Add(student);
			studentContext.SaveChanges();
		}
	}

	public void UpdateStudent(Student student)
	{
		var studentFind = this.Get(student.ID);
		if (studentFind != null)
		{
			studentFind.Name = student.Name;
			studentFind.Contact = student.Contact;
			studentFind.Age = student.Age;
			studentFind.Address = student.Address;
			studentContext.SaveChanges();
		}
	}

	public void RemoveStudent(int id)
	{
		var studObj = studentContext.Students.Find(id);
		if (studObj != null)
		{
			studentContext.Students.Remove(studObj);
			studentContext.SaveChanges();
		}
	}
}

Comments

Submit
0 Comments