错误" EntityType没有定义键"对于复合键

时间:2017-02-13 15:48:57

标签: ef-code-first entity-framework-6

我正在尝试使用实体框架v6.1.3绑定我的数据但是我收到此错误消息 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;    
    }

并且在数据库中我有

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

知道我错过了什么吗? 非常感谢!

1 个答案:

答案 0 :(得分:2)

使用EF,一切都需要属性而不仅仅是“普通”变量。这是必要的,因此EF可以挂钩这些方法。

所以这样:

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

忘记这样做会导致各种难以追溯到实际原因的问题,就像刚刚遇到的那样。