【问题标题】:Linq-to-sql multiple tables queryLinq-to-sql 多表查询
【发布时间】:2014-10-28 09:34:56
【问题描述】:

我有以下方法:

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;
   }
}

这显然行不通。我需要这个方法来返回这个连接的结果。最好改成List。我想知道这是否可以在不必创建包含两个表的属性的类的情况下完成,因为我正在使用linq-to-sql 并且已经为每个表提供了类。

为了使这个查询/方法正常工作,我应该返回什么类型?

【问题讨论】:

  • 我刚刚更新了我的答案,有用吗?

标签: c# linq linq-to-sql


【解决方案1】:

下面的方法会将连接的结果返回到一个列表中。

您需要通过连接来指定要从两个表中使用的列。您必须指定列(属性),因为 join 不知道需要选择哪些。还有它的好习惯。选择所需的列,而不是选择所有列属性。

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
   }
}

是的,如果您不想使用自定义类,那么上面的代码将不需要创建额外的自定义类。

如下调用方法:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-22
    • 2010-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-09
    • 1970-01-01
    相关资源
    最近更新 更多