Miguel Moura Miguel Moura -3 years ago 285
C# Question

Property name in a type must be unique

I am using Entity Framework 5 and I have the following entities:

public class User {
public Int32 Id { get; set; }
public String Username { get; set; }
public virtual ICollection<CLaim> CLaims { get; set; }
}

public class Claim {
public Int32 Id { get; set; }
public String Type { get; set; }
public String Value { get; set; }
public virtual User User { get; set; }
}


A few notes about these entities:


  1. In User entity the Id is the PK;

  2. In Claim entity the Id is a FK and is equal to User.Id;

  3. In Claim entity the PK is composite from (Id, Type, Value)



So I have the following SQL for these entities:

create table dbo.Users
(
Id int identity not null
constraint PK_Users_Id primary key clustered (Id),
Username nvarchar (120) not null
constraint UQ_Users_Username unique (Username)
);

create table dbo.Claims
(
Id int not null,
[Type] nvarchar (200) not null,
Value nvarchar (200) not null,
constraint PK_Claims_Id_Type_Value primary key (Id, [Type], Value),
);

alter table dbo.Claims
add constraint FK_CLaims_Id foreign key (Id)
references dbo.Users(Id) on delete cascade on update cascade;


Finally, the configuration of the entities are as follows:

internal class UserConfiguration : EntityTypeConfiguration<User> {
internal UserConfiguration() : base() {
ToTable("Users");
HasKey(x => x.Id);
Property(x => x.Id).IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(x => x.Username).IsRequired().HasMaxLength(120);
}
}

internal class ClaimConfiguration : EntityTypeConfiguration<Claim> {
internal ClaimMapper() : base() {
ToTable("Claims");
HasKey(x => new { x.Id, x.Type, x.Value });
Property(x => x.Id).IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
Property(x => x.Type).IsRequired().HasMaxLength(200);
Property(x => x.Value).IsRequired().HasMaxLength(200);

HasRequired<User>(x => x.User).WithMany(y => y.Claims).Map(z => { z.MapKey("Id"); });
}
}


THE PROBLEM:

When I try to create a user I get the following error:


Each property name in a type must be unique. Property name 'Id' was already defined.


Does anyone knows what I might be doing wrong?

Answer Source

MapKey is only used if your foreign key column is not exposed as a property in your model. But in your case it is - as property Claim.Id. In that case you must use HasForeignKey instead of MapKey:

HasRequired<User>(x => x.User)
    .WithMany(y => y.Claims)
    .HasForeignKey(x => x.Id);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download