开发者

Having trouble building this small comparison in C#

I'm using Entity Framework as my ORM. I'm trying to get all grade instances where the GradeInstanceId is equal to X, and the Year is equal to this year.

int currentYear = DateTime.Now.Year;
private void LoadGradeInstances()
{
    GradeInstanceRepository repo = new GradeInstanceRepository();
    int gradeId = 5; //For example.
    cmbGradeInstance.DataSource = repo.FindAll().Where(g => g.GradeId == gradeID && g.Year == currentYear);
}

I'm receiving the error:

Operator '==' cannot be applied to operands of type 'System.DateTime?' and 'int'

How can I solve this comparison?

Thank you.开发者_如何学Go


Your issue is that you are trying to compare an Object to a primitive. Try comparing the DateTime's year component to your int year variable.


Try this. Not for sure what type 'Year' so I can't say for sure it will work.

    int currentYear = DateTime.Now.Year;
private void LoadGradeInstances()
{
    GradeInstanceRepository repo = new GradeInstanceRepository();
    int gradeId = 5; //For example.
    cmbGradeInstance.DataSource = repo.FindAll().Where(g => g.GradeId == gradeID && g.Year.Year == currentYear);
}


It could be that currentYear is of DateTime. In that case you may need to do

currentYear.Year

Or g.Year is of DateTime in that case you need to do

g.Year >= datetimeStartOfYear && g.Year <= datetimeEndOfYear


Try g.Year.Year:

(g => g.GradeId == gradeID && g.Year.Year == currentYear)


Try this:

int currentYear = DateTime.Now.Year;
private void LoadGradeInstances()
{
    GradeInstanceRepository repo = new GradeInstanceRepository();
    int gradeId = 5; //For example.
    cmbGradeInstance.DataSource = repo.FindAll().Where(g => g.GradeId == gradeID && g.Year.Value.Year == currentYear);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜