Error "EntityType has no key defined" for composite keys

ef-code-first entity-framework-6

Question

I am trying to bind my data using entity framework v6.1.3 but I am getting this error message EntityType has no key defined. Define the key for this EntityType. (I am having a composite key)

I've tried the following approaches:

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;

}

and this

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; }

    }

and also this

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

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

and in the DB I have

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

Any idea what am I missing? Thanks a lot!

1
0
2/13/2017 4:00:43 PM

Accepted Answer

With EF, everything needs to be properties and not just 'plain' variables. This is needed so EF can hook into those methods.

So like this:

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

Forgetting to do this causes all kinds of problems that can be hard to trace back to the actual cause, as you have just encountered.

2
2/13/2017 4:00:43 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow