如何在LINQ中进行内部联接

时间:2015-11-19 09:02:28

标签: c# sql linq

我有一个Linq语句将数据检索到我的JAVASCRIPT表中。 我想要做的是显示广告系列归档的对象。我需要将它加入我的MSCDB.Tbl_Users到Campaign表。有人可以尝试给我一些帮助吗?我是LINQ的新手。

MSCDatabaseDataContext MSCDB = new MSCDatabaseDataContext();
            var q = from row in MSCDB.Tbl_Campaigns
                    where row.CampaignStatus == 4
                    select new ArchiveReport

                    {
                        CampaignId = row.CampaignId,
                        CampaignName = row.CampaignName,
                        CampaignDescription = row.CampaignDescription,
                        CurrentStatus = row.EndDate >= DateTime.Now && row.StartDate <= DateTime.Now ? "Active" : row.StartDate >= DateTime.Now ? "Pending" : row.CampaignStatus == 4 ? "Archived" : "Closed",
                        CampaignStartDatesS = Convert.ToDateTime(row.StartDate).Date + " - " + Convert.ToDateTime(row.EndDate).Date,
                        Discount = Convert.ToInt32(row.Discount),
                        Target = Convert.ToInt32(row.Target),
                        Uptake = Convert.ToInt32(row.Uptake),
                        DateArchived = Convert.ToDateTime(row.DateArchived),
                        ArchivedBy = Convert.ToInt32(row.ArchivedBy)
                    };

2 个答案:

答案 0 :(得分:1)

我不确定你的数据库结构如何,但如果Tbl_UsersCampaignId,你应该这样做:

MSCDatabaseDataContext MSCDB = new MSCDatabaseDataContext();
var q = from row in MSCDB.Tbl_Campaigns
    //here is your join
    join usr in MSCDB.Tbl_Users on row.CampaignId equals usr.CampaignId
    //-------------------------
    where row.CampaignStatus == 4
    select new ArchiveReport

    {
        //Here how you can jet values from user table
        UserName = usr.Name,
        //-------------------------
        CampaignId = row.CampaignId,
        CampaignName = row.CampaignName,
        CampaignDescription = row.CampaignDescription,
        CurrentStatus = row.EndDate >= DateTime.Now && row.StartDate <= DateTime.Now ? "Active" : row.StartDate >= DateTime.Now ? "Pending" : row.CampaignStatus == 4 ? "Archived" : "Closed",
        CampaignStartDatesS = Convert.ToDateTime(row.StartDate).Date + " - " + Convert.ToDateTime(row.EndDate).Date,
        Discount = Convert.ToInt32(row.Discount),
        Target = Convert.ToInt32(row.Target),
        Uptake = Convert.ToInt32(row.Uptake),
        DateArchived = Convert.ToDateTime(row.DateArchived),
        ArchivedBy = Convert.ToInt32(row.ArchivedBy)
    };

答案 1 :(得分:1)

示例代码是

var q= from row in MSCDB.Tbl_Campaigns
                join user in MSCDB.Tbl_Users 
                on row.UserId equals user.ID
                     select row;