2

我有 linq 的问题,我有以下代码:

        Models.Users user = null;
        foreach (var item in db.Users)
        {
            if (item.username.Equals(username))
            {
                ausgabe = true;
                user = item;
            }
        }

        // linq, does not work
        user = null;
        var test = from u in db.Users
                   where u.username.Equals(username)
                   select u;
        user = (Models.Users)test;

在运行时我得到一个错误,因为测试我 IQueryable,但如何进行这个对话?

4

2 回答 2

3

当您想要执行查询时,问题似乎是向用户投射查询,所以可能:

user = test.SingleOrDefault();

(另见FirstOrDefault()First()Single()

另外,为了方便和可读性,我可以建议:

where u.username == username

(在常规代码中,这也避免了存在的问题u.usernamenull从而导致 a NullReferenceException

于 2012-06-28T07:21:30.483 回答
2

您的演员表是错误的,您想将对象列表分配给一个对象:

   var test = from u in db.Users
               where u.username.Equals(username)
               select u;
    user = (Models.Users)test; // wrong part.

user = test.FirstOrDefault();

或者

 user = db.Users.FirstOrDefault(x=>x.username.Equals(username));
于 2012-06-28T07:22:48.263 回答