我有一個產品表使用UPC作爲主鍵的一部分。一切都很好,直到產品沒有UPC,推薦的解決方法是在8004 +身份證號碼和8005 +身份證號碼之間生成一個號碼。實體框架4:如何在不使用標識字段的情況下插入下一個最高數字?
如果在事務中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
我將如何做到這一點在實體框架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
所以現在的問題是一樣的:你怎麼能產生實體框架4,即最少的最高可用數量,你怎麼會在LINQ的重寫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