我正在使用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; }
}
关于这些实体的一些注释:
所以我对这些实体有以下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”。
有谁知道我可能做错了什么?
答案 0 :(得分:35)
MapKey
。但在你的情况下,它是 - 作为财产Claim.Id
。在这种情况下,您必须使用HasForeignKey
代替MapKey
:
HasRequired<User>(x => x.User)
.WithMany(y => y.Claims)
.HasForeignKey(x => x.Id);
答案 1 :(得分:4)
除了Slauma的回答
HasForeignKey
不适用于1:1,如果您仍然需要它,您只需使用不带参数的WithMany
HasRequired<User>(x => x.User).WithMany().HasForeignKey(x => x.Id);
HasRequired(x => x.City).WithMany().HasForeignKey(x => x.CityId);
答案 2 :(得分:0)
当引用属性的类型不匹配时,也可能发生这种情况。例如:
public string TipId { get; set; }
代替
public int TipId { get; set; }