gpt4 book ai didi

c# - 类型中的属性名称必须是唯一的

转载 作者:可可西里 更新时间:2023-11-01 08:01:02 25 4
gpt4 key购买 nike

我正在使用 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"); });
}
}

问题:

当我尝试创建用户时出现以下错误:

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

有谁知道我可能做错了什么?

最佳答案

MapKey 仅在您的外键列未作为模型中的属性公开时才使用。但在您的情况下,它是 - 作为属性 Claim.Id。在这种情况下,您必须使用 HasForeignKey 而不是 MapKey:

HasRequired<User>(x => x.User)
.WithMany(y => y.Claims)
.HasForeignKey(x => x.Id);

关于c# - 类型中的属性名称必须是唯一的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17639599/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com