我有一个模型,该模型保存列表月份1月-12月。我希望将用户设置为日志示例的开始日期12月26日至1月25日或1月1日-1月31日
public class SalaryMonth
{
public int Id { get; set; }
public int StartMonth { get; set; }
public int StartDay { get; set; }
public int EndMonth { get; set; }
public int EndDay { get; set; }
public string Name { get; set; }
}
如何根据提供的日期获取SalaryMonth,但是这是我的业务逻辑一个月,总是返回null
namespace Contracts.Attendances
{
public interface IAttendanceService
{
Task<SalaryMonth> GetASalaryMonthByDate(DateTime date);
}
public class AttendanceService : IAttendanceService
{
/.../
public async Task<SalaryMonth> GetASalaryMonthByDate(DateTime date) {
var day = date.Day;
var month = date.Month;
var result = await _context.SalaryMonths.
.FirstOrDefaultAsync(p => (p.StartMonth == month && p.StartDay >= day && p.StartDay <= day)
|| ( p.EndMonth == month && p.EndDay >= day && p.EndDay <= day));
return result;
}
}
}
Json来自数据库
{
"SalaryMonth": [
{
"Id": "3",
"StartMonth": "2",
"StartDay": "26",
"EndMonth": "3",
"EndDay": "25",
"Name": "March"
},
{
"Id": "4",
"StartMonth": "3",
"StartDay": "26",
"EndMonth": "4",
"EndDay": "25",
"Name": "April"
},
{
"Id": "5",
"StartMonth": "4",
"StartDay": "26",
"EndMonth": "5",
"EndDay": "25",
"Name": "May"
},
{
"Id": "6",
"StartMonth": "5",
"StartDay": "26",
"EndMonth": "6",
"EndDay": "25",
"Name": "June"
},
{
"Id": "7",
"StartMonth": "6",
"StartDay": "26",
"EndMonth": "7",
"EndDay": "25",
"Name": "July"
},
{
"Id": "8",
"StartMonth": "7",
"StartDay": "26",
"EndMonth": "8",
"EndDay": "25",
"Name": "August"
},
{
"Id": "9",
"StartMonth": "8",
"StartDay": "26",
"EndMonth": "9",
"EndDay": "25",
"Name": "September"
},
{
"Id": "10",
"StartMonth": "9",
"StartDay": "26",
"EndMonth": "10",
"EndDay": "25",
"Name": "October"
},
{
"Id": "11",
"StartMonth": "10",
"StartDay": "26",
"EndMonth": "11",
"EndDay": "25",
"Name": "November"
},
{
"Id": "12",
"StartMonth": "11",
"StartDay": "26",
"EndMonth": "12",
"EndDay": "25",
"Name": "December"
},
{
"Id": "2",
"StartMonth": "2",
"StartDay": "26",
"EndMonth": "2",
"EndDay": "25",
"Name": "February"
},
{
"Id": "1",
"StartMonth": "12",
"StartDay": "26",
"EndMonth": "1",
"EndDay": "25",
"Name": "January"
}
]
}
如何查询记录以允许用户从提供的日期获得薪水月份。示例用户提供了26/12/2019到26/01/2020之间的任何日期,结果必须为1月,因为该日期为 Jan Month ,因为Jan StartMonth是12,StartDate 26,EndMonth是1,EndDate 25
答案 0 :(得分:1)
所以我想我知道您要做什么。如果我理解正确,那么您的linq电话中的逻辑就有些混乱了。 给定任意一天,该天不能小于或等于某个日期,也不能大于或等于该同一日期,除非它是同一日期。
所以您需要这样做:
C#代码:
.FirstOrDefaultAsync(p => (p.StartMonth == month && p.StartDay <= day) || ( p.EndMonth == month && p.EndDay >= day ));
希望这会有所帮助。