Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF 4.1 EntityType has no key - composite

I have just upgraded to the latest EF 4.1 code-first using NuGet and now I am receiving an error regarding my mapping.

I have this class

public class UserApplication
{
    [Key, Column(Order = 0)]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int UserId { get; set; }

    [Key, Column(Order = 1)]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int ApplicationId { get; set; }

    [ForeignKey("ApplicationId")]
    public virtual Application Application { get; set; }

    public DateTime SubscribedDate { get; set; }
}

And I am getting this error:

System.Data.Edm.EdmEntityType: : EntityType 'UserApplication' has no key defined. Define the key for this EntityType.
System.Data.Edm.EdmEntitySet: EntityType: EntitySet 'UserApplications' is based on type 'UserApplication' that has no keys defined.

I can however make it work using the Fluent API like this

modelBuilder.Entity<UserApplication>().HasKey(obj => new {obj.UserId, obj.ApplicationId });

How come EF doesn't pick up the composite key that I have defined using annotations? I am quite certain that this used to work with an older EF 4.1.

like image 486
kfuglsang Avatar asked Aug 08 '11 08:08

kfuglsang


2 Answers

I've solved the issue. I've just added additional key columns:

public class AlbumUser
{
    public Album Album
    {
        get;
        set;
    }

    public IdentityUser User
    {
        get;
        set;
    }

    [Key]
    [Column(Order = 0)]
    [StringLength(128)]
    public string UserId
    {
        get;
        set;
    }

    [Key]
    [Column(Order = 1)]
    public int AlbumId
    {
        get;
        set;
    }
}
like image 177
Teacher Avatar answered Oct 16 '22 09:10

Teacher


Works with Entity Framework 6.1.3. I also added a basic Application class, but used the UserApplication as is (except for DatabaseGeneratedOption. This SQL was generated:

CREATE TABLE [dbo].[UserApplication] (
    [UserId] [int] NOT NULL,
    [ApplicationId] [int] NOT NULL,
    [SubscribedDate] [datetime] NOT NULL,
    CONSTRAINT [PK_dbo.UserApplication] PRIMARY KEY ([UserId], [ApplicationId])
)


CREATE TABLE [dbo].[Application] (
    [ApplicationId] [int] NOT NULL IDENTITY,
    [Name] [nvarchar](max),
    CONSTRAINT [PK_dbo.Application] PRIMARY KEY ([ApplicationId])
)
like image 30
Gert Arnold Avatar answered Oct 16 '22 08:10

Gert Arnold