0

Having a little trouble converting this SQL script to linq. The "fn_Split_t" function simply splits a comma separated value. The part that is confusing me is the group by there as that seems to throw off everything that follows it.

    declare @count int
    select @count = COUNT(*) from  dbo.fn_Split_t(@portfolios)
    select 
         cc.CustodianCommentId
        ,cc.[Message]
        ,Symbol = NULL
        ,cc.DateStamp
        ,cc.AppUser
        ,PositionDate = @date
        ,cc.[Status]
        ,cc.Category
        ,cc.[Group]
    from dbo.CustodianComment cc
    join dbo.CustodianCommentPortfolio ccp on ccp.CustodianCommentId = cc.CustodianCommentId
    join dbo.CustodianPortfolio cp on ccp.CustodianPorfolioId = cp.CustodianPortfolioId
    join dbo.fn_Split_t(@portfolios) s on s.items = cp.PortfolioCode
    where  cp.PositionDate = @date 
    group by cc.CustodianCommentId,  cc.[Message], cc.DateStamp, cc.AppUser, cc.[Status], cc.Category, cc.[Group]
    having count(cc.CustodianCommentId) = @count
    order by cc.DateStamp desc

Attempt number one resulted in the following:

from c in Context.Comments
join pc in Context.PortfolioComments on c.CommentId equals pc.CommentId
join p in Context.Portfolios on pc.PortfolioId equals p.PortfolioId
where portfolios.Contains(p.PortfolioCode)
&& p.PositionDate == EntityFunctions.TruncateTime(date)
group c by c.CommentId into g
where g.Count() > portfolios.Count()
select new
{
   CommentId = c.CommentId,

   Message = c.Message,
   DateStamp = c.DateStamp,
   AppUser = c.AppUser,
   PositionDate = p.PositionDate,
   Status = c.Status,
   Category = c.Category,
   CategoryId = c.CategoryId,
   Group = c.Group
}

However this doesn't work because it says c in the anonymous object is not in scope. portfolios by the way is the same csv string that would have been passed to the @portfolios in the SQL script. I'm am kinda stuck on this one right now so any help would be greatly appreciated! Thank you!

4

1 回答 1

1
 string[] portfoliosArray = portfolios.Split(',', StringSplitOptions.RemoveEmptyEntries);

 from ... in ...
    where portoliosArray.Contains(p.PortfolioCode)
    select ...

当投资组合代码列表包含空格或其他空格时,您可能需要修剪条目:

 string[] portfoliosArray = portfolios.Split(',', StringSplitOptions.RemoveEmptyEntries)
       .Select(s => s.Trim()).Where(s => !string.IsNullOrEmpty(s)).ToArray();

从原始 SQL 中读取,您可能需要:

    where portfoliosArray.All(p => c.PortFolios.PortfolioCode)

或者:

    where c.Portfolios.All(p => portfoliosArray.Contains(p.Portfolio.Code))

虽然我不完全确定你的要求。

于 2013-02-11T17:29:53.947 回答