Home > Back-end >  Foreign Key int Array C#
Foreign Key int Array C#

Time:12-28

I have related table. How can I keep the relationship in this table as an array?

        public int TreatmentId { get; set; }

        [ForeignKey("TreatmentId")]
        public virtual Treatment Treatment { get; set; }

I want to be able to give the TreatmentId here like this; enter image description here

When I make an array and try to migrate, I get the following error;

The property 'ContactPage.TreatmentId' is of type 'int[]' 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'.

   public int[] TreatmentId { get; set; }

   [ForeignKey("TreatmentId")]
   public virtual Treatment Treatment { get; set; }
 

CodePudding user response:

You cannot save an integer array as FK, however I have seen people adding comma separated values as string, but this design is a very bad practice and will cause you many problems.

You need to have a third Table (one of your tables is Treatments, assuming the other one is Patients), like PatientsTreatments:

public class PatientsTreatments
{
    public int PatientId { get; set;}
    public int TreatmentId { get; set;}
}

and then you need to add a new record for each treatment.

  • Related