我有一个Product表,它使用UPC作为主键的一部分。一切都很好,直到产品没有UPC,推荐的解决方法是生成8004 +身份号码和8005 +身份号码之间的数字。
如果UPC在交易中为零,我需要生成一个唯一的UPC,然后只能为那些零作为UPC值的产品检索新的UPC。
在SQL中,我可以这样做:
insert into Product (ID, Name)
select min(pivotTable.value), 'New Product' as Name
from pivotTable
where not exists(
select null as nothing
from product
where pivotTable.value = product.ID ) and
pivotTable.value > 8004000000 and pivotTable.value < 8005000000
select id
from product
where Name = 'New Product' -- assuming Name is unique
我将如何在Entity Framework 4中执行此操作?另外一个问题是,这一切都在一次交易中,因此分配多组缺失的UPC可以为所有新产品分配相同的UPC。
编辑:
我最终创建了一个看起来像这样的视图来获得下一个最高的数字,但EF不会在图表中生成表格,因为它无法确定主键。如果我破解XML,它将一直有效,直到我从数据库更新,这将删除我的更改。
Select min(ID), 'New Product' as Name
from ( select distinct ID
from product p1
where p1.ID > 8004000000 and p1.ID < 8005000000
union
select distinct coalesce( ID, 8004000000) as ID) A
left outer join
( select distinct ID
from product p2
where p2.ID > 8004000000 and p2.ID < 8005000000
union
select distinct coalesce( ID, 8004000000) as ID) B
on A.ID + 1 = B.ID
where B.ID is null
所以问题是一样的:你如何在Entity Framework 4中生成最低的可用数量,即,如何在Linq to Entities中重写上面的SQL查询,或者你怎么能获取要在Entity Framework 4图表中显示的视图,而不编辑在刷新时抛出更改的XML文件?
编辑:这似乎是使用Linq生成下一个可用的:
// Setup our ID list
var prod = DC.Products.Where(p => p.ID > 0 && p.ID < 1000)
.Select(p => p.ID).Distinct();
// Compare the list against itself, offset by 1. Look for "nulls"
// which represent "next highest number doesn't exist"
var q = (from p1 in prod
from p2 in prod.Where(a => a == p1 + 1).DefaultIfEmpty() // Left join
where p2 == 0 // zero is null in this case
select p1).Min();
var r = q + 1; // one higher than current didn't exist, so that's the answer
答案 0 :(得分:0)
不太确定为什么需要这种复杂的计算。但是,如果您需要始终唯一的数据库范围的数字,请查看MSSQL表中的RowVersion
类型。它将为您提供始终唯一的编号,每次更新记录行时都会更改该编号。它对整个数据库来说都是独一无二的。