简体   繁体   English

实体框架,比较复杂类型

[英]Entity framework, compare complex types

How do I compare complex types in queries? 如何比较查询中的复杂类型?

Does not work (always returns null, EDIT: since new version of EF it throws exception): 不起作用(总是返回null,EDIT:由于新版本的EF会引发异常):
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<> db是ObjectContext,PhysObjects是ObjectSet <>

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. 您需要在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;
}

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. 阅读“ MSDN-覆盖准则”以获取更多信息。

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

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

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