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

标签 c# entity-framework

我正在使用 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/

相关文章:

时间:2019-03-17 标签:c#regeximgsrc

c# - 从另一个线程启用/禁用菜单项

entity-framework - 无法删除该对象,因为在 ObjectStateManager 中未找到该对象?

entity-framework - 如何构建工作单元/服务层/存储库,以便它们与 DI (Unity) 和 Moq 一起进行单元测试

c# - 寻找为 Sql 查询和 Windows 窗体创建帮助程序类的指导

c# - 删除/替换国际字符

c# - 用于 Java/C# 的 EDIEL 库

mysql - 通过 Entity Framework 中的多个表获取值?

c# - 如何使用 AutoMapper 更新具有嵌套实体的实体并使用 Entity Framework 保存更新后的实体?

c# - 如何动态使用 SqlFunctions.PatIndex