15

私は Entity Framework 5 を使用しており、次のエンティティがあります。

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

これらのエンティティに関する注意事項:

  1. User エンティティでは、Id は PK です。
  2. Claim エンティティでは、Id は FK であり、User.Id と同じです。
  3. Claim エンティティでは、PK は (Id、Type、Value) から合成されます

したがって、これらのエンティティに対して次の SQL があります。

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;

最後に、エンティティの構成は次のとおりです。

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

問題:

ユーザーを作成しようとすると、次のエラーが表示されます。

型の各プロパティ名は一意である必要があります。プロパティ名 'Id' は既に定義されています。

誰かが私が間違っているかもしれないことを知っていますか?

4

3 に答える 3