Entity Framework 4 / Linq: How to convert from DateTime to string in a query?

后端 未结 4 1141
猫巷女王i
猫巷女王i 2020-12-05 18:22

I have the following query:

from a in Products
select new ProductVM
    {
         id = a.id,
         modified = a.modified.ToString()
    }
4条回答
  •  囚心锁ツ
    2020-12-05 18:56

    Create a new POCO with this structure (I'm assuming that the data type is DateTime):

    public class UserProductVM {
        ...
        private DateTime _modified;
    
        public DateTime SetModified { set { _dateEvent = value; } }
        public string Modified { get { return _modified.ToString("dd MMM yyyy @ HH:mm:ss"); } }
        ...
    }
    

    Then you assign the value to SetModified, changing your code like this:

    from a in Products
    select new UserProductVM
    {
         ...
         SetModified = a.modified
    }
    

    Pay attention i'm using UserProductVM instead ProductVM and SetModified instead modified.

    Then when you get the property Modified, the new POCO is gonna bring it as the string that you formatted.

提交回复
热议问题