E
E
embiid2021-04-09 23:16:42
Entity Framework
embiid, 2021-04-09 23:16:42

How correct is the relation of the models?

I get an error: CREATE UNIQUE INDEX duplicate key when I update-database by EF Core

public class Role : IEntity
    {
        public int Id { get; set; }

        public string Label { get; set; }

        public User User { get; set; }
    }


public class User : IEntity
    {
        public int Id { get; set; }

        public string FirstName { get; set; }

        public int RoleId { get; set; }

        public Role Role { get; set; }
    }


public void Configure(EntityTypeBuilder<Role> entity)
        {
            entity
                .HasKey(key => key.Id);

            entity
                .Property(property => property.Label)
                .HasDefaultValue("Customer")
                .HasMaxLength(20)
                .IsRequired();

            entity
                .HasOne(property => property.User)
                .WithOne(property => property.Role)
                .HasForeignKey<User>(property => property.RoleId);
        }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Ross Man, 2021-04-10
@Rossman

Probably, you want to implement the functionality - one role has several users, it is best to do this according to agreements - connections

public class Role : IEntity
    {
        public int Id { get; set; }

        public string Label { get; set; }

        public ICollection<User> Users { get; set; }
    }


public class User : IEntity
    {
        public int Id { get; set; }

        public string FirstName { get; set; }

        public int RoleId { get; set; }

        public Role Role { get; set; }
    }

Since everything is in order from the key agreement - from the configuration section, leave only
entity
                .Property(property => property.Label)
                .HasDefaultValue("Customer")
                .HasMaxLength(20)
                .IsRequired();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question