如何查询基于rowversion /时间戳值代码第一次实体? [英] How to query Code First entities based on rowversion/timestamp value?

查看:403
本文介绍了如何查询基于rowversion /时间戳值代码第一次实体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我碰到的东西在那里与LINQ得不错,以SQL似乎很钝(或者不可能)与实体框架的情况。具体来说,我已经得到了包括 rowversion 属性的实体(无论是版本和并发控制)。是这样的:

I've run into a case where something that worked fairly well with LINQ to SQL seems to be very obtuse (or maybe impossible) with the Entity Framework. Specifically, I've got an entity that includes a rowversion property (both for versioning and concurrency control). Something like:

public class Foo
{
  [Key]
  [MaxLength(50)]
  public string FooId { get; set; }

  [Timestamp]
  [ConcurrencyCheck]
  public byte[] Version { get; set; }
}



我希望能够采取一个实体作为输入,并找到所有被最近更新的其他实体。是这样的:

I would like to be able to take a entity as input, and find all of the other entities that are more recently updated. Something like:

Foo lastFoo = GetSomeFoo();
var recent = MyContext.Foos.Where(f => f.Version > lastFoo.Version);

现在,在数据库中这会工作:两个 rowversion 值可以相互比较,没有任何问题。我已经使用LINQ to SQL,它映射了 rowversion System.Data.Linq.Binary ,它可以进行比较。 (至少到表达式树可以被映射到数据库的程度。)

Now, in the database this would work: two rowversion values can be compared to one another without any problems. And I've done a similar thing before using LINQ to SQL, which maps the rowversion to System.Data.Linq.Binary, which can be compared. (At least to the extent that the expression tree can be mapped back to the database.)

但是,在代码首先,属性的类型必须是字节] 。和两个阵列不能与常规比较运算符进行比较。有一些其他的方式来编写LINQ到实体就会明白阵列的比较呢?或者要挟阵列成其他类型,这样比较能得到过去的编译器?

But in Code First, the type of the property must be byte[]. And two arrays can't be compared with the regular comparison operators. Is there some other way to write the comparison of the arrays that LINQ to Entities will understand? Or to coerce the arrays into other types so that the comparison can get past the compiler?

推荐答案

您可以使用类SqlQuery写。原始SQL,而不是让它产生

You can use SqlQuery to write the raw SQL instead of having it generated.

MyContext.Foos.SqlQuery("SELECT * FROM Foos WHERE Version > @ver", new SqlParameter("ver", lastFoo.Version));

这篇关于如何查询基于rowversion /时间戳值代码第一次实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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