Convert datetime to a formatted string inside a LINQ-to-entities query

前端 未结 6 896
时光取名叫无心
时光取名叫无心 2020-12-13 19:15

How can I convert DateTime into a formatted string?

This is the line in the following query that needs help:

StartDate = string.Format(\         


        
6条回答
  •  一生所求
    2020-12-13 19:25

    EDIT: Now that I understand the question, I'm giving it another shot :)

    var offer = (from p in dc.CustomerOffer
                         join q in dc.OffersInBranch
                             on p.ID equals q.OfferID
                         where q.BranchID == singleLoc.LocationID
                         let value = (p.OriginalPrice - p.NewPrice) * 100 / p.OriginalPrice
                         orderby value descending
                         select new
                         {
                             Title = p.OfferTitle,
                             Description = p.Description,
                             BestOffer=value,
                             ID=p.ID,
                             LocationID=q.BranchID,
                             LocationName=q.CustomerBranch.BranchName,
                             OriginalPrice=SqlFunctions.StringConvert((decimal)p.OriginalPrice),
                             NewPrice=SqlFunctions.StringConvert((decimal)p.NewPrice),
                             StartDate=p.StartDate
    
                         })
                         .ToList()
                         .Select(x => new Offer()
                         {
                             Title = x.OfferTitle,
                             Description = x.Description,
                             BestOffer=value,
                             ID=x.ID,
                             LocationID=x.BranchID,
                             LocationName=x.CustomerBranch.BranchName,
                             OriginalPrice=x.OriginalPrice,
                             NewPrice=x.NewPrice,
                             StartDate=x.StartDate.ToString("dd.MM.yy")
                         }).First();
    

    I know it's a bit long, but that's the problem with Linq To SQL.

    When you use linq, the database call isn't executed until you use something such as ToList() or First() that results in actual objects. Once that SQL call is executed by the first .First() call, you're now working with .NET types, and can use DateTime stuff.

提交回复
热议问题