将 SQL 转换为 LINQ C#

huangapple go评论77阅读模式
英文:

Converting sql to LINQ C#

问题

以下是翻译好的部分:

我正在使用LLBLGEN Pro Runtime Framework,并获取一个表的实体。
是否可能将此查询转换为LINQ表达式

我迄今为止尝试过这个:

var log1 = config_log.Where(app => app.AppId == 173)
                     .Select(s => new {
                          s.SettingName, 
                          s.SettingValue, 
                          s.RowLstUpdTs, 
                          s.MachineName, 
                          s.RowLstUpdUid})
                     .ToList()
                     .GroupBy(x => x.SettingName); 

但这离我需要的还有很大的差距。
英文:

I'm using LLBLGEN Pro Runtime Framwork and getting an entity of a table.
Is it possible to convert this query to LINQ expression?

SELECT s1.SETTING_NAME, s1.SETTING_VALUE, s1.ROW_LST_UPD_TS, s1.MACHINE_NAME, s1.ROW_LST_UPD_UID
FROM EVENT_MGT.CONFIGURATION_LOG s1
INNER JOIN (
    SELECT SETTING_NAME, MAX(ROW_LST_UPD_TS) ROW_LST_UPD_TS
    FROM EVENT_MGT.CONFIGURATION_LOG
    WHERE APP_ID = 173
--    and ROW_LST_UPD_TS >= CURRENT_TIMESTAMP - 7
    GROUP BY SETTING_NAME
) s2 ON s1.SETTING_NAME = s2.SETTING_NAME AND s1.ROW_LST_UPD_TS = s2.ROW_LST_UPD_TS
WHERE s1.APP_ID = 173;

I tried so far this:

var log1 = config_log.Where(app => app.AppId == 173)
                     .Select(s => new {
                          s.SettingName, 
                          s.SettingValue, 
                          s.RowLstUpdTs, 
                          s.MachineName, 
                          s.RowLstUpdUid})
                     .ToList()
                     .GroupBy(x => x.SettingName); 

But its far from what I need.

答案1

得分: 2

请尝试类似以下的代码:

class Program
{
    static void Main(string[] args)
    {
        int CURRENT_TIMESTAMP = 123;

        List<CONFIGURATION_LOG> logs = new List<CONFIGURATION_LOG>();
        var results = logs.Where(x => (x.APP_ID == 173) && (x.ROW_LST_UPD_TS >= CURRENT_TIMESTAMP - 7))
            .OrderByDescending(x => x.ROW_LST_UPD_TS)
            .GroupBy(x => x.SETTING_NAME)
            .Select(x => x.FirstOrDefault())
            .Select(x => new
            {
                setting_name = x.SETTING_NAME,
                setting_value = x.SETTING_VALUE,
                row_lst_upd_ts = x.ROW_LST_UPD_TS,
                machine_name = x.MACHINE_NAME,
                row_lst_upd_uid = x.ROW_LST_UPD_UID
            }).ToList();
    }
}

public class EVENT_MGT
{
    CONFIGURATION_LOG CONFIGURATION_LOG { get; set; }
}

public class CONFIGURATION_LOG
{
    public string SETTING_NAME { get; set; }
    public string SETTING_VALUE { get; set; }
    public int ROW_LST_UPD_TS { get; set; }
    public string MACHINE_NAME { get; set; }
    public string ROW_LST_UPD_UID { get; set; }
    public int APP_ID { get; set; }
}

这段代码用于演示如何使用C#进行一些操作。

英文:

Try something like this

<!-- begin snippet: js hide: false console: true babel: false -->

   class Program
    {
       
        static void Main(string[] args)
        {
            int CURRENT_TIMESTAMP = 123;

            List&lt;CONFIGURATION_LOG&gt; logs = new List&lt;CONFIGURATION_LOG&gt;();
            var results = logs.Where(x =&gt; (x.APP_ID == 173) &amp;&amp; (x.ROW_LST_UPD_TS &gt;= CURRENT_TIMESTAMP - 7))
                .OrderByDescending(x =&gt; x.ROW_LST_UPD_TS)
                .GroupBy(x =&gt; x.SETTING_NAME)
                .Select(x =&gt; x.FirstOrDefault())
                .Select(x =&gt; new
                {
                    setting_name = x.SETTING_NAME,
                    setting_value = x.SETTING_VALUE,
                    row_lst_upd_ts = x.ROW_LST_UPD_TS,
                    machine_name = x.MACHINE_NAME,
                    row_lst_upd_uid = x.ROW_LST_UPD_UID
                }).ToList();

        }
    }
    public class EVENT_MGT
    {
        CONFIGURATION_LOG CONFIGURATION_LOG { get; set; } 
    }
    public class CONFIGURATION_LOG
    {
        public string SETTING_NAME { get; set; }
        public string SETTING_VALUE { get; set; }
        public int ROW_LST_UPD_TS { get; set; }
        public string MACHINE_NAME { get; set; }
        public string ROW_LST_UPD_UID { get; set; }
        public int APP_ID { get; set; }
    }

<!-- end snippet -->

答案2

得分: 1

你提供了损失信息。也许你想要类似于这个关键词的东西:Entity Framework。请访问此链接

此外,我有一个关于在C#中优化使用SQL查询命令从包含image数据类型列的表中获取数据而不使用Entity Framework的想法,分为3个步骤,附带一个小示例:

步骤0:(默认)创建一个新表。这是我的表TBUsers

CREATE TABLE [dbo].[TBUsers]
(
	[STT] [BIGINT] IDENTITY(1,1) NOT NULL,
	[HoTen] [NVARCHAR](MAX) NOT NULL,
	[MaSo] [NVARCHAR](50) NOT NULL,
	[MatKhau] [NVARCHAR](MAX) NOT NULL,
	[KhoaLop] [NVARCHAR](MAX) NOT NULL,
	[MaTheGui] [NVARCHAR](50) NOT NULL,
	[PhanQuyen] [INT] NOT NULL,
	[ChoPhepHoatDong] [BIT] NOT NULL,
	[NguoiThem] [NVARCHAR](MAX) NOT NULL,
	[NgayThem] [DATETIME] NOT NULL,
	[SoDuKhaDung] [BIGINT] NOT NULL,
	[DangGui] [BIT] NOT NULL,
	[TruyCapLanCuoi] [DATETIME] NULL,
	[ThoiGianGuiCuoi] [DATETIME] NULL,
	[HinhAnh] [IMAGE] NULL,
	[DonGia] [BIGINT] NULL,

    CONSTRAINT [PK_TBUsers] 
        PRIMARY KEY CLUSTERED ([MaTheGui] ASC)
                    WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, 
                          IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, 
                          ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

步骤1:创建一个与上面表对应的新类,并创建2个构造函数,Users

public class Users
{
    public Users()
    { }

    public Users(object sTT, object hoTen, object maSo, object matKhau, object khoaLop, object maTheGui, object phanQuyen, object choPhepHoatDong,
        object nguoiThem, object ngayThem, object soDuKhaDung, object dangGui, object truyCapLanCuoi, object thoiGianGuiCuoi, object hinhAnh, object donGia)
    {
        // 省略构造函数中的代码
    }

    // 属性列表省略
}

步骤2:使用ParseUser函数从数据库中获取Users

public static Users ParseUser(DataRow row)
{
    // 省略ParseUser函数中的代码
    return new Users(stt, hoTen, maSo, matKhau, khoaLop, maTheGui, phanQuyen, choPhepHoatDong, nguoiThem, ngayThem, soDuKhaDung, dangGui,
        truyCapLanCuoi, guiLanCuoi, hinhAnh, donGia);
}

步骤3:使用ParseUser函数轻松获取Users类的实例:

Users user = ParseUser(sqlUtility.GetDataTable($"SELECT * FROM [dbo].[TBUsers] WHERE MaSo = 'xxx' AND ChoPhepHoatDong=1;").Rows[0]);

类似地,你可以创建一个类来检索整个Users,使用任何集合,如List<User>IEnumerable<User>。你可以使用LinQ来查询这些数据。

英文:

You give the loss information. Maybe you want one thing such as this keywork: Entity Framework. Follow this link;

Besides, I have an idea for optimize use of call SQL query command to get data from a table includes columns with image datatype using C# without Entity Framework in 3 steps with a small example:

Step 0: (default) Create a new table. This is my table TBUsers:

CREATE TABLE [dbo].[TBUsers]
(
	[STT] [BIGINT] IDENTITY(1,1) NOT NULL,
	[HoTen] [NVARCHAR](MAX) NOT NULL,
	[MaSo] [NVARCHAR](50) NOT NULL,
	[MatKhau] [NVARCHAR](MAX) NOT NULL,
	[KhoaLop] [NVARCHAR](MAX) NOT NULL,
	[MaTheGui] [NVARCHAR](50) NOT NULL,
	[PhanQuyen] [INT] NOT NULL,
	[ChoPhepHoatDong] [BIT] NOT NULL,
	[NguoiThem] [NVARCHAR](MAX) NOT NULL,
	[NgayThem] [DATETIME] NOT NULL,
	[SoDuKhaDung] [BIGINT] NOT NULL,
	[DangGui] [BIT] NOT NULL,
	[TruyCapLanCuoi] [DATETIME] NULL,
	[ThoiGianGuiCuoi] [DATETIME] NULL,
	[HinhAnh] [IMAGE] NULL,
	[DonGia] [BIGINT] NULL,

    CONSTRAINT [PK_TBUsers] 
        PRIMARY KEY CLUSTERED ([MaTheGui] ASC)
                    WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, 
                          IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, 
                          ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

Step 1: create a new class that corresponds to the table above and create 2 constructors, Users:

    public class Users
    {
        public Users()
        { }

        public Users(object sTT, object hoTen, object maSo, object matKhau, object khoaLop, object maTheGui, object phanQuyen, object choPhepHoatDong,
            object nguoiThem, object ngayThem, object soDuKhaDung, object dangGui, object truyCapLanCuoi, object thoiGianGuiCuoi, object hinhAnh,object donGia)
        {
            STT = sTT.ToString();
            HoTen = hoTen.ToString();
            MaSo = maSo.ToString();
            MatKhau = matKhau.ToString();
            KhoaLop = khoaLop.ToString();
            MaTheGui = maTheGui.ToString();
            PhanQuyen = phanQuyen.ToString();
            ChoPhepHoatDong = choPhepHoatDong.ToString();
            NguoiThem = nguoiThem.ToString();
            NgayThem = ngayThem.ToString();
            SoDuKhaDung = soDuKhaDung.ToString();
            DangGui = dangGui.ToString();
            TruyCapLanCuoi = truyCapLanCuoi.ToString();
            ThoiGianGuiCuoi = thoiGianGuiCuoi.ToString();
          
            HinhAnh = hinhAnh==System.DBNull.Value?null: (byte[])hinhAnh;
            DonGia = donGia.ToString();
            Color = (bool)choPhepHoatDong;
        }

        public string STT { get; set; }
        public string HoTen { get; set; }
        public string MaSo { get; set; }
        public string MatKhau { get; set; }
        public string KhoaLop { get; set; }
        public string MaTheGui { get; set; }
        public string PhanQuyen { get; set; }
        public string ChoPhepHoatDong { get; set; }
        public string NguoiThem { get; set; }
        public string NgayThem { get; set; }
        public string SoDuKhaDung { get; set; }
        public string DangGui { get; set; }
        public string TruyCapLanCuoi { get; set; }
        public string ThoiGianGuiCuoi { get; set; }
        public byte[] HinhAnh { get; set; }
        public string DonGia { get; set; }
        public bool Color { get; set; }
    }
}

Step 2: Get Users from database with the ParseUser function:

    public static Users ParseUser(DataRow row)
    {
        var stt = row[&quot;STT&quot;];
        var hoTen = row[&quot;HoTen&quot;];
        var maSo = row[&quot;MaSo&quot;];
        var matKhau = row[&quot;MatKhau&quot;];
        var khoaLop = row[&quot;KhoaLop&quot;];
        var maTheGui = row[&quot;MaTheGui&quot;];
        var phanQuyen = row[&quot;PhanQuyen&quot;];
        var choPhepHoatDong = row[&quot;ChoPhepHoatDong&quot;];
        var nguoiThem = row[&quot;ChoPhepHoatDong&quot;];
        var ngayThem = row[&quot;ChoPhepHoatDong&quot;];
        var soDuKhaDung = row[&quot;SoDuKhaDung&quot;];
        var dangGui = row[&quot;DangGui&quot;];
        var truyCapLanCuoi = row[&quot;TruyCapLanCuoi&quot;];
        var guiLanCuoi = row[&quot;ThoiGianGuiCuoi&quot;];
        var hinhAnh = row[&quot;HinhAnh&quot;] == System.DBNull.Value ? null : row[&quot;HinhAnh&quot;];
        var donGia = row[&quot;DonGia&quot;];

        return new Users(stt, hoTen, maSo, matKhau, khoaLop, maTheGui, phanQuyen, choPhepHoatDong, nguoiThem, ngayThem, soDuKhaDung, dangGui,
            truyCapLanCuoi, guiLanCuoi, hinhAnh, donGia);
    }

Step 3: Easily take an instance of Users class with ParseUser function:

Users user = ParseUser(sqlUtility.GetDataTable($&quot;SELECT * FROM [dbo].[TBUsers] WHERE MaSo = &#39;xxx&#39; AND ChoPhepHoatDong=1;&quot;).Rows[0]);

Similarly, you can create a class to retrieve the entire Users using any collection such as List&lt;User&gt; or IEnumerable&lt;User&gt;. You can use LinQ to query with this data.

答案3

得分: 0

感谢jdweng,我找到了如何获取我需要的确切内容:

var results = config_log.Where(x => x.AppId == 173)
                        .OrderByDescending(x => x.RowLstUpdTs).ToList()
                        .GroupBy(x => x.SettingName)
                        .Select(x => new
                        {
                            setting_name = x.Select(y => y.SettingName).FirstOrDefault(),
                            setting_value = x.Select(y => y.SettingValue).FirstOrDefault(),
                            row_lst_upd_ts = x.Select(y => y.RowLstUpdTs).FirstOrDefault(),
                            machine_name = x.Select(y => y.MachineName).FirstOrDefault(),
                            row_lst_upd_uid = x.Select(y => y.RowLstUpdUid).FirstOrDefault()
                        }).ToList();
英文:

Thanks to jdweng, I figured out how to get exactly what I need:

var results = config_log.Where(x =&gt; x.AppId == 173)
                	                .OrderByDescending(x =&gt; x.RowLstUpdTs).ToList()
                	                .GroupBy(x =&gt; x.SettingName )
                	                .Select(x =&gt; new
                	                { 
	                                    setting_name = x.Select(y =&gt; y.SettingName).FirstOrDefault(),
                		                setting_value = x.Select(y =&gt; y.SettingValue).FirstOrDefault(),
                		                row_lst_upd_ts = x.Select(y =&gt; y.RowLstUpdTs).FirstOrDefault(),
                		                machine_name =  x.Select(y =&gt; y.MachineName).FirstOrDefault(),
                		                row_lst_upd_uid = x.Select(y =&gt; y.RowLstUpdUid).FirstOrDefault()
                                    }).ToList();

huangapple
  • 本文由 发表于 2020年1月7日 01:18:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/59616317.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定