在Entity Framework中慎用Guid?

最近在使用EF和Data Service的时候遇到了一系列奇怪的问题,估计是我用Guid作为主键外键的原因。

如:

var c2 = dc.Categories.Where(o => o.CategoryID == c.CategoryID).First();

CategoryID 是long的类型,能正常运行。

而:

var customers = dc.Customers.Where(o => o.CustomerID == new Guid("4c65d18f-9ff1-4c31-accd-1fea164ef507"));

CustomerID 是Guid的类型,就找不到数据。

必须改为:

Guid gid=new Guid("4c65d18f-9ff1-4c31-accd-1fea164ef507");
var customers = dc.Customers.Where(o => o.CustomerID == gid);

下面是一些参考资料:

http://msdn.microsoft.com/en-us/library/dd283139.aspx

http://geekswithblogs.net/SudheersBlog/archive/2009/06/11/132758.aspx

另外,在用Guid作为外键的类型,在添加明细表的数据时,无法正确添加。如下的表结构:

Product

ProductID Guid
CategoryID Guid
ProductName String

Category

CategoryID Guid
CategoryName String

在编写如下代码的时候,不能正确运行:

DataServiceContext dc=new DataServiceContext();

Category c=comboBox1.SelectedItem as Category;

Product p=new Product()

{

Category=c,

ProductName=”some good”

}

dc.AddToProduct(p);

dc.SetLink(p,”Category”,p.Category);

dc.SaveChanges();

如果把以上ID的数据类型改为String或Number的话,以上代码就能正确运行。

分享到: 更多
原文地址:https://www.cnblogs.com/redmoon/p/1636908.html