this is my first post on the forum. I can't find any posts that answers my problem. If you do find one, please reply the link so I can take a look at it.
这是我在论坛上的第一篇文章。我找不到任何能解决我问题的帖子。如果你找到了,请回复链接,我可以看一下。
I am trying to update a DateTime column in SQL Server using C#.
我试图使用C#更新SQL Server中的DateTime列。
In the first console application, I have already created an object:
在第一个控制台应用程序中,我已经创建了一个对象:
NewCollegeEntities context = new NewCollegeEntities();
College college = new College();
college.collegeName = "BCIT";
college.established = new DateTime(1960, 1, 1);
context.Colleges.Add(college);
context.SaveChanges();
Now, in the second console application, I am trying to add a day to the objected just created:
现在,在第二个控制台应用程序中,我正在尝试向刚刚创建的对象添加一天:
NewCollegeEntities context = new NewCollegeEntities();
College college = (from c in context.Colleges
where c.collegeName == "BCIT"
select c).FirstOrDefault();
college.established.Value.AddDays(1);
context.SaveChanges();
When I run the second console application, the results are the same as first console application-1960, 1, 1. It seems like I am not committing any changes to the database.
当我运行第二个控制台应用程序时,结果与第一个控制台应用程序-1960,1,1相同。看起来我没有对数据库进行任何更改。
Please help me understand what's going on and how to go about fixing this. Also let me know if you require more information! Thanks!
请帮助我了解正在发生的事情以及如何解决这个问题。如果您需要更多信息,请告诉我们!谢谢!
1 个解决方案
#1
3
This is a common oversight. The AddDays()
method (and other similar methods) doesn't actually modify the value on which you invoke it. It returns a new DateTime
which has the modified value.
这是一种常见的疏忽。 AddDays()方法(以及其他类似方法)实际上并不会修改您调用它的值。它返回一个具有修改值的新DateTime。
Simply use that new DateTime
:
只需使用新的DateTime:
college.established = college.established.Value.AddDays(1);
#1
3
This is a common oversight. The AddDays()
method (and other similar methods) doesn't actually modify the value on which you invoke it. It returns a new DateTime
which has the modified value.
这是一种常见的疏忽。 AddDays()方法(以及其他类似方法)实际上并不会修改您调用它的值。它返回一个具有修改值的新DateTime。
Simply use that new DateTime
:
只需使用新的DateTime:
college.established = college.established.Value.AddDays(1);