如何在视图上设置主键

时间:2018-12-27 10:11:59

标签: c# sql

由于创建的视图没有主键,因此我无法更新模型。错误消息显示“没有定义主键”

ALTER VIEW VwSupplyStatement ADD PRIMARY KEY PK_VwSupplyStatement DISABLE 
NOVALIDATE;
IF OBJECT_ID ('dbo.VwSupplyStatement') IS NOT NULL
DROP VIEW dbo.VwSupplyStatement
GO
CREATE  VIEW [dbo].[VwSupplyStatement]
AS
SELECT
    MAX(Objid) AS Objid,
    MAX(PaymentHeaderId) AS PaymentHeaderId, 
    MAX(PalletNo) AS PalletNo,
    MAX(SequenceNo) AS SequenceNo,  
    MAX(Season) AS Season,
    --MAX(OrganizationId) AS OrganizationId,
    MAX(AccountId) AS AccountId,
    MAX(ShipmentDocumentNumber) AS DocumentNo,
    MAX(AccountFullDescription) AS AccountDescription,
    MAX(ShipmentLoadName) AS Vessel,
    MAX(ShipmentRegionLId) AS TargetMarketId,
    MAX(ContainerNo) AS ContainerNo,
    MAX(QualityCertified) AS QualityCertified,
    MAX(IncoTerm) AS IncoTerm,
    MAX(BuyTerm) AS BuyTerm,
    MAX(TotalpaymentvsPO) AS TotalpaymentvsPO,
    MAX(TripNumber) AS Voyage,
    MAX(DepatureDate) AS DepatureDate,
    MAX(Cartons) AS Cartons,
    MAX(Advance1Currency) AS Advance1Currency,
    MAX(CASE WHEN InvoiceNo ='AD1' THEN 'AD1' END) AS ADvance1InvoiceNo,
    MAX(CASE WHEN InvoiceNo ='AD1' THEN Advanceinvoices END) AS Advance1invoices,
    MAX(CASE WHEN InvoiceNo ='AD1' THEN Amount END) AS AD1Amount,
    MAX(CASE WHEN InvoiceNo ='AD1' THEN AmountPaid END) AS Amount1Paid,
    MAX(CASE WHEN InvoiceNo ='AD1' THEN AmountDue END) AS Amount1Balance,
    ---------------------------------------------------------------------
    MAX(CASE WHEN InvoiceNo ='AD2' THEN 'AD2' END) AS ADvance2InvoiceNo,
    MAX(CASE WHEN InvoiceNo ='AD2' THEN Advanceinvoices END) AS Advance2invoices,
    MAX(CASE WHEN InvoiceNo ='AD2' THEN Amount END) AS AD2Amount,
    MAX(CASE WHEN InvoiceNo ='AD2' THEN AmountPaid END) AS Amount2Paid,
    MAX(CASE WHEN InvoiceNo ='AD2' THEN AmountDue END) AS Amount2Balance,
     ---------------------------------------------------------------------
    MAX(CASE WHEN InvoiceNo ='AD3' THEN 'AD3' END) AS ADvance3InvoiceNo,
    MAX(CASE WHEN InvoiceNo ='AD3' THEN Advanceinvoices END) AS Advance3invoices,
    MAX(CASE WHEN InvoiceNo ='AD3' THEN Amount END) AS AD3Amount,
    MAX(CASE WHEN InvoiceNo ='AD3' THEN AmountPaid END) AS Amount3Paid,
    MAX(CASE WHEN InvoiceNo ='AD3' THEN AmountDue END) AS Amount3Balance
    --MAX(NetPaymentDIP) AS TotalFnl
    --MAX(CreditAmount) AS CreditAmount
FROM dbo.VwSupplyStatementBase
GROUP BY ShipmentDocumentNumber

我如何对此视图强制执行主键?

是否可以修改此sql代码,以便在Visual Studio上更新模型时不会损坏?

1 个答案:

答案 0 :(得分:1)

您不能在视图上创建主键,可以在视图上创建索引。有关更多信息,SQL server indexed views

为了解决您的问题

强制实体框架将列用作主键,请使用ISNULL

SELECT
INULL(MAX(Objid),-1) AS Objid ,.... from FROM dbo.VwSupplyStatementBase
GROUP BY ShipmentDocumentNumber