简体   繁体   中英

Linq-to-sql multiple tables query

I have a following method:

public List<object> GetLoginValues(String user, String pass)
{
   using (db = new DCDataContext())
   {
      List<object> x = (from u in db.users
                      join t in db.userTypes on u.type equals t.typeID
                      where u.loginName == user &&
                      u.password == pass &&
                      u.isActive == true
                      select new
                      {
                          u.userID,
                          u.loginName,
                          u.userCode,
                          u.type,
                          u.team,
                          t.typeName
                      }).ToList();
      return x;
   }
}

Which obviously doesn't work. I need this method to return the result of this join. Preferably into a List . I want to know if this can be done without having to make a class containing the properties for both tables, since I'm using linq-to-sql and already have classes for every table.

What type should I return in order to make this query/method work properly?

The below method will return the result of join into a List.

You need to specify the columns, which you are going to use from the two tables by joining it. You must specify the columns (property) because join doesn't know which need to be selected. And also its good practice. Selecting required columns instead of selecting all the columns properties.

public dynamic GetLoginValues(String user, String pass)
{
    using (db = new DCDataContext())
    {
        var x = (from u in db.users
               join t in db.userTypes on u.type equals t.typeID
               where u.loginName == user &&
               u.password == pass &&
               u.isActive == true
               select new
                   {
                       u.userID,
                       u.loginName,
                       u.userCode,
                       u.type,
                       u.team,
                       t.typeName
                   }).ToList();
      return x; //returns the list of values
   }
}

Yes if you don't want to use custom classes, then the above code will not require to create additional custom classes.

Call the Method Like below:

YourClassName dbObj = new YourClassName();
var loginDetailsList = dbObj.GetLoginValues("RJK", "123456");

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