简体   繁体   English

Linq 实体加入不起作用

[英]Linq to entities join not working

Any idea why the following code will not compile?知道为什么以下代码无法编译吗?

IEnumerable users;
using (var ent = new GatekeeperEntities())
{
    users = from t1 in ent.Users
            join t2 in ent.UserStatus1 on t1.ID equals t2.UserId
            where t2.ExpirationDateTime != null
            select new {t1.ID, t1.Name, t1.UserName, t2.Status };
    }

foreach (var user in users)
{
    user.ID; // Cannot resolve symbol ID
}

Restructure your code as below.如下重构您的代码。

using (var ent = new GatekeeperEntities())
{
    var users = from t1 in ent.Users
        join t2 in ent.UserStatus1 on t1.ID equals t2.UserId
        where t2.ExpirationDateTime != null
        select new {t1.ID, t1.Name, t1.UserName, t2.Status };

    foreach (var user in users)
    {
        user.ID;
    }
}

The contents of an IEnumerable are of type System.Object, you need to use the var keyword instead so that the compiler will infer that users is of type IEnumerable<T> for some anonymous type T. If you want to use an anonymous type, loop over the elements inside the scope of the using block. IEnumerable的内容是 System.Object 类型,您需要使用 var 关键字,以便编译器会推断 users 是某个匿名类型 T 的类型IEnumerable<T> 。如果要使用匿名类型,循环遍历 using 块的 scope 内的元素。

  user.Id; <-----Cannot resolve symbol ID

According to your code it should be user.ID (upper case not lower case) - capitalization matters.根据您的代码,它应该是user.ID (大写而不是小写) - 大小写很重要。

Also you have user declared as IEnumerable - so you won't get any properties of the type it really is, just the properties available on IEnumerable - declare it as var and use it inside the using statement, or create a class instead of using an anonymous type.此外,您将user声明为IEnumerable - 因此您不会获得它真正类型的任何属性,只是IEnumerable上可用的属性 - 将其声明为 var 并在 using 语句中使用它,或创建 class 而不是使用匿名类型。

Try to cast your user object within the loop.尝试在循环中投射您的用户 object。

foreach (var user in users)   
{
    ((User)user).ID;
}

And remember: what you usually accomplish with joins in SQL, can be simply done by moving along relations in EF:请记住:您通常使用 SQL 中的连接来完成的工作,可以通过在 EF 中移动关系来简单地完成:

users = from t2 in ent.UserStatus.Include("User") 
where t2.ExpirationDateTime != null
select t2

This gives you the UserStatus es you want, and you can access the User of each UserStatus through the property User that is propabely defined in your model.这为您提供了所需的UserStatus es,您可以通过在 model 中适当定义的属性User访问每个UserStatusUser

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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