简体   繁体   中英

asp.net LinqDataSource query multiple tables with join

I'm currently working on an ASP.NET 4.5 application using LinqToSQL. I use a asp:GridView control. In my data source query method, I need to query all data from 2 tables from SQL Server with almost identical fields.

My DB class one:

private partial class AdOld 
{
   private int PK;
   private string Text; 
}

My DB class two:

private partial class AdNew 
{
   private int PK;
   private string Text;
   private bool IsActive;
}

My LinqDataSource1_Selecting method for the GridView looks like this:

protected void LinqDataSource1_Selecting(object sender, LinqDataSourceSelectEventArgs e)
{
   var ctx = new MyContext();

   var result = new MyContext().AdOld;
   // I would need to add a query to select something like MyContext().AdOld.AdNew into a Model of AdOld

   e.Result = result;
}

Do you know how to (select * from 2 tables) query multiple tables in 1 linq query? I need all entries of both tables apart from IsActive in table AdNew.

Thanks so much!!

Just try something like that;

var query = from ao in AdOld
            from an in AdNew 
            select new
            {
                ao,
                an
            };

In your case, also you can use Union ;

var adOld = ctx.AdOld.Select(ao => new Ad { Pk = ao.PK, Text = ao.Text }).ToList();
var adNew = ctx.AdNew.Where(an => an.IsActive).Select(an => new Ad { Pk = an.PK, Text = an.Text }).ToList();
var result = adOld.Union(adNew).ToList();

public class Ad
{
    public int Pk { get; set; }

    public string Text { get; set; }
}

Do you want to do a Union? Try something like this

var ao = ctx.AdOld.Select(x => new { x.PK, x.Text})
var an = ctx.AdNew.Select(x => new { x.PK, x.Text})
var query = ao.Union(ae);

I would create a new class called something like OldAndNew, and have 2 query's select into a list of that class. That way your new class can have some unique identifier for the new data set as there may be duplicate PK's.

    public class OldAndNew
    {
      public int NewPK;
      public int OriginalPK;
      public string Text;
    }

And Then:

int number = 0;
var listOfBoth = new List<OldAndNew>();
            var x = AdOld.Select(y => new OldAndNew()
            {
                NewPK = number++,
                OriginalPK = y.PK,
                Text = y.Text
            });
            var y = AdNew.Select(y => new OldAndNew()
            {
                NewPK = number++,
                OriginalPK = y.PK,
                Text = y.Text
            });
listOfBoth.Add(x);
listOfBoth.Add(y);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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