Home > Net >  How to disallow duplicate rows in EF core 5.0 with relational tables?
How to disallow duplicate rows in EF core 5.0 with relational tables?

Time:10-09

I used 3 classes to structure the group.

My database provider is Microsoft SQL Server.

public class GroupType
{
        [Key]
        public int GroupTypeId { get; set; }
        [MaxLength(100)]
        public string GroupTypeExpalin { get; set; }
}

public class Groups
{
    [Key]
    public int GroupId { get; set; }
    [MaxLength(200)]
    public string GroupName { get; set; }
    public GroupType GroupType { get; set; }
}

[Index(nameof(EntityId), nameof(GroupDet), IsUnique = true)] //not allow duplicate Rows
public class GroupDetail
{
        [Required]
        public  string EntityId { get; set; }
        [Required]
        public Groups GroupDet { get; set; }
}

I get this error when I try to do add-migration

The property 'GroupDetail.GroupDet' is of type 'Groups' which is not supported by the current database provider. Either change the property CLR type, or ignore the property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.

CodePudding user response:

The correct design here is to have a compound key. That way you don't need a separate unique index, and you optimize for accessing all the Group details for a particular group by having the GroupId be the leading index key.

public class Group
{
    public int GroupId { get; set; }

    public virtual ICollection<GroupDetail> GroupDetails { get; set; } = new HashSet<GroupDetail>();
}

public class GroupDetail
{
    [Required]
    public int GroupId { get; set; }
    [Required]
    public string EntityId { get; set; }

    public Group Group { get; set; }
}

and then

    protected override void OnModelCreating(ModelBuilder builder)
    {                        
        builder.Entity<Group>();
        builder.Entity<GroupDetail>().HasKey(nameof(GroupDetail.GroupId), nameof(GroupDetail.EntityId));

CodePudding user response:

database table can not have column of type Groups. it is unknown for database. you must have some thing like this:

[Required]
    public int GroupId { get; set; }

which GroupId is a FK of Groups

  • Related