将外键值与LINQ进行比较 [英] Comparing foreign key values with LINQ

查看:57
本文介绍了将外键值与LINQ进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为Activity的EF项,它包含一个指向名为Location的项的外键(数据库中的字段是LocationID)。我在添加一个新的Activity之前使用linq进行检查,在同一个位置中还没有一个具有相同名称的Activity,但是我无法让它工作。我试过了

I've got an EF item called Activity which contains a foreign key pointing to an item called Location (the field in the database is LocationID). I do a check using linq before adding a new Activity that there is not already an Activity with the same name in the same Location, but I can't get it to work. I tried

if ((from c in Connection.Instance.Entities.Activity where c.Name == Item.Name && c.LocationReference == Item.LocationReference select c).Count() > 0)
    return InsertActivityResult.AlreadyExists;


(Item是所有这些中插入的对象)

失败并显示错误"LINQ to Entities不支持指定的类型成员'LocationReference'。"
我然后尝试了<

(Item is the object being inserted in all these)

This fails with the error "The specified type member 'LocationReference' is not supported in LINQ to Entities."

I then tried

if ((from c in Connection.Instance.Entities.Activity where c.Name == Item.Name && c.Location.ID == Item.Location.ID select c).Count() > 0)
    return InsertActivityResult.AlreadyExists;


但我得到一个空引用异常。

我可以通过

But I get a null reference exception.

I can obviously fix this by doing

if ((from c in Connection.Instance.Entities.Activity.Include("Location") where c.Name == Item.Name && c.Location.ID == Item.Location.ID select c).Count() > 0)
    return InsertActivityResult.AlreadyExists;


但这意味着我在数据库中发生了一个真正不需要的连接!我想要做的就是根据外键的价值进行检查,而不是从位置表中加载任何东西。

我是否遗漏了一些明显的东西?

谢谢

But this means I have a join happening in the database which really is not required! All I want to do is check based on the value of the foreign key, without ever loading anything from the Location table.

Am I missing something obvious?

Thanks

推荐答案

这是EF v1的限制 - 我们不支持类似存储的外键。所有关系都是显式关联,因此您必须在此处进行连接。在即将发布的EF v2(使用.NET 4.0)中,我们将提供外键支持。

谢谢,
祖宾
This is the limitation of EF v1 - we don't have support for store-like foreign keys. All relations are explicit associations so you have to do the join here. In the upcoming release of EF v2 (with .NET 4.0), we will have foreign key support.

Thanks,
Zubin


这篇关于将外键值与LINQ进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆