开发者

Linq to entities join not working

开发者 https://www.devze.com 2023-03-07 23:06 出处:网络
Any idea why the following code will not compile? IEnumerable users; using (var ent = new GatekeeperEntities())

Any idea why the following code will not compile?

IEnumerable users;
using (var ent = new GatekeeperEntities())
{
    users = from t1 in e开发者_运维问答nt.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.


Try to cast your user object within the loop.

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


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

According to your code it should be user.ID (upper case not lower case) - capitalization matters.

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.


And remember: what you usually accomplish with joins in SQL, can be simply done by moving along relations in EF:

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

This gives you the UserStatuses you want, and you can access the User of each UserStatus through the property User that is propabely defined in your model.

0

精彩评论

暂无评论...
验证码 换一张
取 消