实体框架,比较复杂类型

发布于 2024-12-21 10:07:00 字数 538 浏览 3 评论 0原文

如何比较查询中的复杂类型?

不起作用(总是返回 null,编辑:因为新版本的 EF 它会抛出异常):
DbVector3 pos = new DbVector3() { X = 0, Y = 0, Z = 0};
db.PhysObjects.FirstOrDefault(s => s.Position == pos);

工作原理:
DbVector3 pos = new DbVector3() { X = 0, Y = 0, Z = 0};
db.PhysObjects.FirstOrDefault(s => s.Position.X == pos.X && s.Position.Y == pos.Y && s.Position.Z == pos.Z); ?

有什么方法可以使第一个示例正常工作吗

编辑: 抱歉,我可能只在标题中提到这是实体框架。

db是ObjectContext,PhysObjects是ObjectSet<>;

How do I compare complex types in queries?

Does not work (always returns null, EDIT: since new version of EF it throws exception):
DbVector3 pos = new DbVector3() { X = 0, Y = 0, Z = 0};
db.PhysObjects.FirstOrDefault(s => s.Position == pos);

Works:
DbVector3 pos = new DbVector3() { X = 0, Y = 0, Z = 0};
db.PhysObjects.FirstOrDefault(s => s.Position.X == pos.X && s.Position.Y == pos.Y && s.Position.Z == pos.Z);

Is there any way to make first example working?

EDIT:
Sorry, I probably mention only in title that this is entity framework.

db is ObjectContext, PhysObjects is ObjectSet<>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

椵侞 2024-12-28 10:07:00

您需要重写 DbVector 类中的 Equals 函数,以便在进行比较时它将用于比较 2 个对象。

protected override bool Equals(object comparer)
{
    DbVector3 compareObj = obj as DbVector3;

    return compareObj.X == this.X && compareObj.Y == this.Y && compareObj.Z == this.Z;
}

您也可以对 == 和 != 运算符执行相同的操作。类似于下面的内容:

public static bool operator ==(DbVector3 a, DbVector3 b)
{
   return a.X == b.X && a.Y == b.Y && a.Z == b.Z;
}

public static bool operator !=(DbVector3 a, DbVector3 b)
{
   return !(a == b);
}

阅读 MSDN -覆盖指南了解更多信息。

You need to override the Equals function in your DbVector class, so that when comparisons are made it will be used to compare 2 objects.

protected override bool Equals(object comparer)
{
    DbVector3 compareObj = obj as DbVector3;

    return compareObj.X == this.X && compareObj.Y == this.Y && compareObj.Z == this.Z;
}

You can also do the same for the == and != operators. Something similar to below :

public static bool operator ==(DbVector3 a, DbVector3 b)
{
   return a.X == b.X && a.Y == b.Y && a.Z == b.Z;
}

public static bool operator !=(DbVector3 a, DbVector3 b)
{
   return !(a == b);
}

Have a read of MSDN - Guidelines for Overriding for more information.

泼猴你往哪里跑 2024-12-28 10:07:00

不,不支持,除非两个值都在数据库中。

No, it's not supported, unless both values are in database.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文