繁体   English   中英

如何在“按查询分组”中不使用linq的情况下调用C#方法

[英]how to call a C# method without linq in “Group by query”

我编写了一个运行良好的LINQ查询,该LINQ查询具有一个group by语句,该语句使用C#方法将DateTime从Miladi转换为hejri。 现在我的目的是 :用原始sql编写此linq查询

这是我的NewsModel类:

public class News
{
    public News()
    {
        Months = new List<string>();
    }        
    public int NewsID { get; set; }
    [Required]        
    public string FaTitle { get; set; }        
    public string FaBody { get; set; }        
    public string EnTitle { get; set; }        
    public string EnBody { get; set; }        
    public bool IsImageActive { get; set; }        
    public string NewsImage { get; set; }        
    public string NewsImage2 { get; set; }        
    public bool IsArchived { get; set; }        
    public bool IsDeleted { get; set; }
    public byte[] RowVersion { get; set; }
    [DataType(DataType.DateTime)]        
    [DisplayFormat(DataFormatString = "{0:yyyy/MM/dd HH:mm:ss}", ApplyFormatInEditMode = true)]
    public DateTime DateUpdate { get; set; }
    [DataType(DataType.DateTime)]        
    [DisplayFormat(DataFormatString = "{0:yyyy/MM/dd HH:mm:ss}", ApplyFormatInEditMode = true)]
    public DateTime DateCreate { get; set; }
    public int CategoryID { get; set; }
    [ForeignKey("CategoryID")]
    public virtual Category Category { get; set; }
    [NotMapped]
    public int Years { get; set; }
    [NotMapped]
    public List<String> Months { get; set; }
}
}

在我的控制器中:

var Archives = from Records in news
    group Records by new { Years = date.GetYear(Records.DateUpdate, ConvertTime.UTCtoIran) } into GYears
    select new { Years = GYears.Key.Years, Months = (from r in GYears group r by date.GetMonthName(r.DateUpdate) into Gmonths select Gmonths.Key) }.ToExpando();

ViewBag.Archive = Archives;

现在我想对原始sql查询执行此操作,正如您在LINQ查询中看到的那样,我使用了date.GetYeardate.GetMonthName方法,它们是C#方法,但我无法在诸如"select date.GetYear(foo) ..."

根据您的评论,您希望获得带有表记录中相应月份列表的年份,而无需使用本地功能:

string query = "select DISTINCT DATEPART(YEAR, dbo.News.DateUpdate) as Year, "
             + "DATEPART(YEAR, dbo.News.DateUpdate) as Month"
             + "from dbo.News";

List<DataHolder> A = db.News.SqlQuery(query).ToList();

var results = (from a in A
                group a by a.Year into grp
                select new
                {
                    Year = grp.Key,
                    Months = grp.Select(x => x.Month).ToList()
                }).ToList();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM