我正在使用 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; }
}
关于这些实体的一些说明:
- 在用户实体中,Id 是 PK;
- 在 Claim 实体中,Id 是一个 FK 并且等于 User.Id;
- 在 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”。
有谁知道我可能做错了什么?