Cosmin
Cosmin

Reputation: 585

Passing month parameter from binded datepicker to linq method MVVM EF

I am looking for a way to pass the selected month from the date picker to my query in order to make the query dynamic. How do I replace the 9 with the month binded to the datepicker? I was thinking of something along the lines of a.sMonth = DateTime.Month(MDate)) but it doesn't work. Simple suggestions are more than welcome. Thank you!

PS: the sMonth from the table is long.

namespace Location.ViewModel
{
    public class LocationViewModel: INotifyPropertyChanged
    {


        public LocationViewModel()
        {
            var db = new DailyEntities();
            Efficiency = Convert.ToDecimal(db.LocationKPI.Where(a => a.sMonth == 9).Select(a => a.Efficiency).FirstOrDefault());
        }

        private DateTime _mDate = DateTime.Now;

        public DateTime MDate
        {
            get { return _mDate; }
            set { _mDate = value; OnPropertyChanged("MDate"); }
        }

        decimal efficiency;

        public decimal Efficiency
        {
            get { return efficiency; }
            set
            {
                efficiency = value;
                OnPropertyChanged("Efficiency");
            }
        }


        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName = null)
        {
            if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

Upvotes: 0

Views: 54

Answers (1)

twoleggedhorse
twoleggedhorse

Reputation: 5048

The following code will get the number 9 from today's date which is the 30th September.

        var MDate = new DateTime();
        MDate = DateTime.Now;

        var month = 0;

        int.TryParse(MDate.ToString("MM"), out month);

I've used the MDate variable name so that it fits your existing code so you can ignore the first two lines.

DateTime.ToString("MM") gets the month in the format "09" but if we try to compare it with the integer 9, that integer will be implicitly converted into a string "9". Since "9" and "09" do not match, we have to convert "09" into an integer. int.TryParse() is the safest way to do this.

Now you have the month in a variable, you can use it in your query.

    public LocationViewModel()
    {
        var db = new DailyEntities();

        // Get the month from the date picker
        var month = 0;
        int.TryParse(MDate.ToString("MM"), out month);

        Efficiency = Convert.ToDecimal(db.LocationKPI.Where(a => a.sMonth == month).Select(a => a.Efficiency).FirstOrDefault());
    }

Upvotes: 1

Related Questions