1

I am having problem with converting the DateTime I am collecting from the database to localtime with LINQ. A LINQ query won't let me use ToLocalTime() and I can't seem to get any fix outside the query to work with the anonymous type of list.

Here is the LINQ query from the controller :

                    // GET: api/Scan
    public object Getv_Update_ComplianceStatusAll()
    {
        var dato = DateTime.Now.AddYears(-1);


        var scan = (from n in db.C_RES_COLL_NO9000AC
                    join s in db.v_Update_ComplianceStatusAll on n.MachineID equals s.ResourceID
                    join u in db.v_UpdateInfo on s.CI_ID equals u.CI_ID
                    join c in db.v_CICategoryInfo on u.CI_ID equals c.CI_ID
                    where (n.MachineID == s.ResourceID) && (u.DateRevised > dato) 
                    group s by new { n.Name } into grp
                    select new
                    {
                        Name = grp.Key.Name,
                        StatusScan = grp.Max(t=> t.LastStatusCheckTime)


                    });


        return scan;
    }

This is my attemt at a fix outside the query :

            var newScan = scan.ToList();

        foreach (var s in newScan)
        {

            s.StatusScan = s.StatusScan.ToLocalTime();
        }

        return newScan;

The converstion works, but it returns "Error 306 Property or indexer 'AnonymousType#1.StatusScan' cannot be assigned to -- it is read only"

So, how do I convert the UTC to local time in the controller (before I return anything to the website)?

2
  • have you tried to use a strongly typed variable instead? I.e.: Creating a ViewModel? Commented May 8, 2015 at 5:22
  • Do you need local time of the server or local time of the client? Commented May 8, 2015 at 5:29

2 Answers 2

1

Yes, Anonymous Type is handy, but it is a bad idea to return it from a method -- Outsider do not know what actually the object is. It is recommended to create a strong type to store the result and return IEnumerable<ScanItem>. Then you are able to modify the result.

public class ScanItem
{
    public string Name { get; set; }
    public datetime StatusScan { get; set; }
}

If you must use Anonymous Type, You can build a new list like this

scan.ToList().Select(i => new {Name = i.Name, StatusScan = i.StatusScan.ToLocalTime()});
Sign up to request clarification or add additional context in comments.

Comments

0
    var newScan = scan.ToList();

    foreach (var s in newScan)
    {
        s.StatusScan = s.StatusScan.ToLocalTime();
    }

    return newScan;

your newScan is a List, you cannot directly assign

s.StatusScan = s.StatusScan.ToLocalTime();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.