gpt4 book ai didi

c# - 无法将字符串转换为 DateTime

转载 作者:太空宇宙 更新时间:2023-11-03 19:03:10 25 4
gpt4 key购买 nike

我在将字符串转换为 DateTime 时遇到问题,这是错误

enter image description here

我使用了此链接中显示的解决方案 enter link description here并使用 DateTime.Parse,但我一直收到此错误

这是我的类(class)表:

 public partial class Schedule : BaseEntity
{

public string Day { get; set; }
public string Note { get; set; }
public DateTime Begin { get; set; }
public DateTime End { get; set; }

}

请帮忙,谢谢更新:这是查询

var Schedules = new List<Schedule>
{
new Schedule
{
Day="Lundi", Note="note", Begin=Convert.ToDateTime("2013-04-24 17:47:03"),
End=Convert.ToDateTime("2013-05-24 17:47:03"),
ClassId = context.Classes.Where(c=>c.Libel=="Class 1").FirstOrDefault().Id,
SubjectLevelId = context.SubjectLevels.Where(cbv=>cbv.Coef==1).FirstOrDefault().Id,
ClassRoomId = context.ClassRooms.Where(c=>c.Libel=="ClassRoom1").FirstOrDefault().Id,
TeacherId = context.Teachers.Where(c=>c.FirstName=="mouna").FirstOrDefault().Id,
SchoolYearId= context.SchoolYears.Where(f=>f.Begin==DateTime.Parse("15/09/2015")).FirstOrDefault().Id
},
};
Schedules.ForEach(s =>
{
s.ObjectState = Repository.Pattern.Infrastructure.ObjectState.Added;
context.Schedules.Add(s);
context.SaveChanges();
});

最佳答案

将您的代码更改为如下内容:

var beginDateTime = Convert.ToDateTime("2013-04-24 17:47:03");
var endDateTime = Convert.ToDateTime("2013-05-24 17:47:03");
var schoolYearBeginDate = DateTime.Parse("15/09/2015");
var Schedules = new List<Schedule>
{
new Schedule
{
Day="Lundi",
Note="note",
Begin = beginDateTime,
End=endDateTime,
ClassId = context.Classes.Where(c=>c.Libel=="Class 1").FirstOrDefault().Id,
SubjectLevelId = context.SubjectLevels.Where(cbv=>cbv.Coef==1).FirstOrDefault().Id,
ClassRoomId = context.ClassRooms.Where(c=>c.Libel=="ClassRoom1").FirstOrDefault().Id,
TeacherId = context.Teachers.Where(c=>c.FirstName=="mouna").FirstOrDefault().Id,
SchoolYearId= context.SchoolYears.Where(f=>f.Begin==schoolYearBeginDate).FirstOrDefault().Id
},
};

此外,这些最终会抛出空引用异常:

context.Classes.Where(c=>c.Libel=="Class 1").FirstOrDefault().Id

将它们更改为:

context.Classes.Where(c=>c.Libel=="Class 1").Select(c => c.Id).FirstOrDefault()

如果 ClassId不可为空,那么您应该这样做:

context.Classes.Where(c=>c.Libel=="Class 1").First().Id

关于c# - 无法将字符串转换为 DateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32668679/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com