2017-02-13 63 views
0

我試圖綁定我的數據使用實體框架v6.1.3,但我收到此錯誤消息EntityType沒有定義密鑰。爲此EntityType定義密鑰。 (我有一個複合鍵)錯誤「EntityType沒有定義密鑰」複合鍵

我嘗試以下方法:

public class CommunicationCollection 
{ 
    [Key, Column(Order = 0)] 
    [ForeignKey("FK_CommunicationCollection_Communication")] 
    public Guid CommunicationId; 

    [Key, Column(Order = 1)] 
    [ForeignKey("FK_CommunicationCollection_Collection")] 
    public Guid CollectionId; 

} 

public class CommunicationCollection 
    { 
     [Key, Column(Order = 0)] 
     [ForeignKey("FK_CommunicationCollection_Communication")] 
     public Guid CommunicationId; 

     [Key, Column(Order = 1)] 
     [ForeignKey("FK_CommunicationCollection_Collection")] 
     public Guid CollectionId; 

     public virtual Communication Communication { get; set; } 
     public virtual Collection Collection { get; set; } 

    } 

而且這個

public class CommunicationCollection 
    { 
     [Key, Column(Order = 0)] 
     public Guid CommunicationId; 

     [Key, Column(Order = 1)] 
     public Guid CollectionId;  
    } 

,並在DB我有

CREATE TABLE [CommunicationCollection](
    [CommunicationId] [uniqueidentifier] NOT NULL, 
    [CollectionId] [uniqueidentifier] NOT NULL, 
CONSTRAINT [PK_CommunicationCollection] PRIMARY KEY CLUSTERED 
(
    [CommunicationId] ASC, 
    [CollectionId] ASC 
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80) ON [PRIMARY] 
) ON [PRIMARY] 

GO 

ALTER TABLE [CommunicationCollection] WITH CHECK ADD CONSTRAINT [FK_CommunicationCollection_Collection] FOREIGN KEY([CollectionId]) 
REFERENCES [Collection] ([CollectionId]) 
GO 

ALTER TABLE [CommunicationCollection] CHECK CONSTRAINT [FK_CommunicationCollection_Collection] 
GO 

ALTER TABLE [CommunicationCollection] WITH CHECK ADD CONSTRAINT [FK_CommunicationCollection_Communication] FOREIGN KEY([CommunicationId]) 
REFERENCES [Communication] ([CommunicationId]) 
GO 

ALTER TABLE [CommunicationCollection] CHECK CONSTRAINT [FK_CommunicationCollection_Communication] 
GO 

任何想法我錯過了什麼? 非常感謝!

回答

2

有了EF,一切都需要屬性而不僅僅是'普通'變量。這是必要的,所以EF可以掛鉤到這些方法中。

所以這樣的:

public Guid CommunicationId { get; set; } 
public Guid CollectionId { get; set; } 

忘記這樣做會導致各種問題,可能很難追溯至實際原因,正如你剛纔遇到的。

+0

謝謝!它解決了我的問題 – WNB

相關問題