【问题标题】:Load foreign key value with linq to entities使用 linq 将外键值加载到实体
【发布时间】:2009-08-31 13:42:17
【问题描述】:

我有一个表 Admins,它创建了用户和位置之间的关系:

ID - numeric (PK)
UserId - uniqueidentifier (FK to UserId in aspnet_Users table)
LocationId - numeric

现在我要执行命令:

IQueryable<decimal> location_ids = (from m in _db.Admins
                                    where m.UserId.Equals( new Guid("c5d3dc0e-81e6-4d6b-a9c3-faa802e10b7d")) && m.LocationId.Equals(conf.umisteni.Budova.ID)
                                    select m.LocationId);

但由于某种原因(我猜 UsersId 是 FK)m.UserId 无法解析。所以我尝试使用

m.aspnet_UsersReference.Value.UserId

然后是决定声明

if (!location_ids.Any())

异常失败

System.NotSupportedException: The specified type member 'aspnet_UsersReference' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

我应该怎么做才能获得可枚举的 LocationIds 列表?

提前致谢。

【问题讨论】:

    标签: c# asp.net linq


    【解决方案1】:

    您缺少一个“用户”和一个点:

    var location_ids = (from m in _db.Admins
                        where m.Users.UserId.Equals( 
                            new Guid("c5d3dc0e-81e6-4d6b-a9c3-faa802e10b7d")) &&   
                            m.LocationId.Equals(conf.umisteni.Budova.ID)
                        select m.LocationId);
    

    本质上,您需要直接使用“用户”关系。

    【讨论】:

    • 显然我忘记解释表 aspnet_Users。它的主要属性是 UserId - PK 和 uniqueidentifier。所以不,点不存在。
    • 好的,然后连接点。您在 Users 属性上有一个关系。我回答的要点是您没有使用它。我猜错了键的名称和关系,但答案仍然是正确的方向:使用关系而不是绕过它。然后您的查询将在 LINQ to Entities 中工作。不过,我会用另一个对正确名称的猜测来更新我的答案。
    猜你喜欢
    • 2011-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多