简体   繁体   中英

How to create a relationship or primary key with Fluent API in asp.core?

Good afternoon, I ran into the problem of creating relationships when learning asp.core, did the registration and authorization on the site through Identity, and made the classes:

public class User : IdentityUser
{ 
    [Key]
    public string Id { get; set; }
    public IEnumerable<User> Pupils { get; set; }
    public int SubLevel { get; set; }
    public int Score { get; set; }

    public virtual ICollection<ProxyUserGroup> ProxyUserGroups { get;set; } = new List<ProxyUserGroup>(); 
}


 [Table("ProxyUserGroups")]
 public class ProxyUserGroup 
 {
    [Key]
    [Column(Order = 0)]
    public string UserId { get; set; }
    [ForeignKey("UserId")]
    public virtual User User { get; set; }

    [Key]
    [Column(Order = 1)]
    public int UserGroupId { get; set; }
    [ForeignKey("UserGroupId")]
    public virtual UserGroup UserGroup { get; set; } 
 }


 [Table("UserGroups")]
 public class UserGroup 
 {
    [Key]
    public int Id { get; set; }

    public string Name { get; set; }

    public virtual ICollection<ProxyUserGroup> ProxyUserGroups { get; set; } = new List<ProxyUserGroup>();
 }

Then I did the migration to the database (before that I did the hands of the table but could not overcome the error and decided to do the migration)

Table ProxyUserGroup

 create table ProxyUserGroups (
 UserId nvarchar(450) not null
 constraint FK_ProxyUserGroups_User_UserId
 references AspNetUsers on delete cascade,
 UserGroupId int not null
 constraint FK_ProxyUserGroups_UserGroups_UserGroupId
 references UserGroups on delete cascade,
 constraint PK_ProxyUserGroups
 primary key (UserId, UserGroupId),
 constraint AK_ProxyUserGroups_UserGroupId_UserId
 unique (UserGroupId, UserId) )

Table UserGroups

create table UserGroups (
Id int identity
constraint PK_UserGroups
primary key,
Name nvarchar(max) )

And context

 protected override void OnModelCreating(Microsoft.EntityFrameworkCore.ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<ProxyUserGroup>()
            .HasKey(t => new { t.UserId, t.UserGroupId });

        modelBuilder.Entity<ProxyUserGroup>()
            .HasOne<User>(e => e.User)
            .WithMany(t => t.ProxyUserGroups)
            .HasForeignKey(e => e.UserId);

        modelBuilder.Entity<ProxyUserGroup>()
            .HasOne<UserGroup>(e => e.UserGroup)
            .WithMany(t => t.ProxyUserGroups)
            .HasForeignKey(e => e.UserGroupId);
    }

After launching the site displays:

InvalidOperationException: Entity type 'ProxyUserGroup' has a composite key defined with data annotations. To set a composite primary key, use fluent API.

But if you go to the site in incognito mode, then everything is fine until you try to log in and then throws it away:

InvalidOperationException: Entity type 'ProxyUserGroup' has a composite key defined with data annotations. To set a composite primary key, use fluent API.

User user = await userManager.FindByEmailAsync (model.Email); // error is still here

From the first error I realized that in modelBuilder.Entity ().HasKey (t => new {t.UserId, t.UserGroupId}); the primary key is not generated (a composite of two external keys), but the second one still has a problem with IdentityUser (which was not previously). What exactly is wrong and what needs to be corrected? Thank you in advance.(Sorry for my English).

Entity type 'ProxyUserGroup' has a composite key defined with data annotations. To set a composite primary key, use fluent API.

This is becuase EF Core does not support creating a composite key using the Key attribute. You have to use the only Fluent API HasKey() function in EF Core . So remove Key attributes from ProxyUserGroup class as follows:

[Table("ProxyUserGroups")]
public class ProxyUserGroup
{
    public string UserId { get; set; }
    public virtual User User { get; set; }

    public int UserGroupId { get; set; }
    public virtual UserGroup UserGroup { get; set; } 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM