简体   繁体   中英

C# - Updating DateTime column in SQL Server

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#.

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.

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!

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.

Simply use that new DateTime :

college.established = college.established.Value.AddDays(1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM