使用LINQ从带有联接的两个表中获取信息

本文关键字:两个 信息 获取 LINQ 使用 | 更新日期: 2023-09-27 18:24:39

我有一个linq语句来填充两个标签。问题是,这些信息来自两张表。我有一个加入来加入这两个表格,除了我无法从我的活动表格中获得我的条款和条件。它只会拾取RedemptionLog表的列。有人帮忙吗?

MSCDatabaseDataContext MSCDB = new MSCDatabaseDataContext();
            var q = from row in MSCDB.Tbl_RedemptionLogs 
                    join d in MSCDB.Tbl_Campaigns on row.CampaignId equals d.CampaignId
                    orderby row.VoucherCode descending
                    select row;
            var SeshVoucherDisplay = q.First();
            lblCode.Text = SeshVoucherDisplay.VoucherCode;
            lblTerms.Text = SeshVoucherDisplay

对于SeshVoucherDisplay变量,它只从RedemptionLogs表中获取,但我进行了联接?有什么帮助吗?

使用LINQ从带有联接的两个表中获取信息

试试这样的东西:

var SupJoin = from row in MSCDB.Tbl_RedemptionLogs
              join d in MSCDB.Tbl_Campaigns on row.CampaignId equals d.CampaignId
              orderby row.VoucherCode descending
              select new { Id = row.ID, SupplierName = row.SupplierName, 
               CustomerName = d.CompanyName };

列名只是为了举例说明。把你自己的放在那里。然后,您可以对其应用First并使用该特定变量。

希望这能有所帮助。

通过编写select row,您要求LINQ只返回row

如果您想要这两个元素,则需要同时请求这两个,例如通过编写select new { row, d }

在本例中,

var foo =
    new []
    {
        new { Id = 1, Name = "a" },
        new { Id = 2, Name = "b" },
        new { Id = 3, Name = "c" }
    };
var bar =
    new []
    {
        new { Id = 1, Name = "d" },
        new { Id = 2, Name = "e" },
        new { Id = 3, Name = "f" }
    };
var baz =
    from a in foo
    join b in bar on a.Id equals b.Id
    select new { a, b };
var qux =
    from a in foo
    join b in bar on a.Id equals b.Id
    select new { a, b };

baz中,您只能找到foo的列表,在qux中,您可以找到foo及其bar的列表。

试试这个:

var query = (from row in MSCDB.Tbl_RedemptionLogs
                                 join d in MSCDB.Tbl_Campaigns on row.CampaignId equals d.CampaignId)
                                 orderby row.VoucherCode descending
                                 select new
                                 {
                                    columnname = row.columnname
                                 });

在编写select row时,您与在from row in MSCDB.Tbl_RedemptionLogs中定义的行相关。

然而,如果你想要两个表中的数据,你必须写一些类似的东西:

select new { 
    // the properties of row
    Redemption = row.redemption, 
    // the properties of d
    Campaign = d.CampaignID // alternativly use may also use row.CampaignID, but I wanted to show you may acces all the members from d also 
}