简体   繁体   中英

How to create a datetime variable with millisecond in c#? (blazor)

private Task OnProjectCreated()
{
    DateTime now = DateTime.Now.AddMilliseconds(1000);

    ProjectModel newProject = new ProjectModel
    {        
        ProjectName = "ProjectA",
        ProjectUpdated = now
    }

    _db.InsertProject(newProject);
    var currentProject = _db.GetProjectByTime<ProjectModel>(now);

    //here, the currentProject object is passing to the parent component(balzor)
    return ProjectCreated.InvokeAsync(currentProject);
    
}

I want to fetch a project from database by DateTime but the DateTime variable 'now' has no milliseconds therefore I get an error like this 'Sequence contains no elements'. So I have added AddMilliseconds(1000) but it is still not working. I think that 'now' variable does not match with Project.ProjectUpdated which is saved in the database.

I have controlled the Project table in sql server management studio and there all ProjectUpdated are saved with milliseconds but when I use 'now' as an arg in _db.GetProjectByTime(now) has no milliseconds. How can I solve it? Thank you in advance!

public ProjectModel GetProjectByTime<ProjectModel>(DateTime dateTime)
     {
         string sql = $"select * from Projects where ProjectUpdated = 
         '{dateTime}'";
         var data = _accessDb.GetData<ProjectModel>(sql);

         return data;
     }

the problem is that, ProjectUpdated in db is saved like this:2021-06-07 17:46:28.747 but when I use 'now' as arg in _db.GetProjectByTime(now) it looks like this: 2021-06-07 17:46:28 I mean without milliseconds (as I have controlled by break points at running)

I changed the string sql to

string sql = $"select * from Projects where ProjectUpdated = CONVERT(datetime, '{dateTime}')";

and this is working now without problem.

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