0

I set up a database with ef core code first management. I have two related tables.I want to insert data into a table. but since it has a relationship with the other table, it tries to throw data into the other table. whereas I only want to record a table. how do i do this?

code:

  1. table
  public class JobTable
        {
            [Key]
            public int ID_JOB { get; set; }
            public JobType JobType { get; set; }
            public string JOB_KEY { get; set; }
            public TimeSpan JOB_TIME { get; set; }
            public int? DAY { get; set; }
            public Boolean IS_ACTIVE { get; set; }
            public string? DESCRIPTION { get; set; }
            public CustomUser CustomUser { get; set; }
        }
  1. table:
public class JobType
    {
        [Key]
        public int ID_JOB_TYPE { get; set; }
        public string JOB_TYPE_NAME { get; set; }
        public List<JobTable> jobTable { get; set; }
    }

ef code:

  context.JobTable.Add(jobTable);
            
  context.SaveChanges();

i just want to add data to 'jobtable' table. but it tries to throw data into the 'jobtype' table as well, since it is related to the 'jobtype' table. idont want this. how can I do it?

Batu han
  • 33
  • 8

1 Answers1

0

The current way that you define the JobTable will also create a new record for JobType when inserting the JobTable record.

Instead, modify the JobTable to apply a foreign key property (JobTypeId) to define a relationship to the JobType table.

public class JobTable
{
    ...

    public int JobTypeId { get; set; }
    
    public virtual JobType JobType { get; set; }

}

public class JobType
{
    ...

    public ICollection<JobTable> JobTables { get; set; }
}

During inserting the new JobTable record, you need to provide the JobType's Id into the entity data to be inserted.


Reference

One-to-Many Relationship Conventions in Entity Framework Core (Convention 4)

Yong Shun
  • 35,286
  • 4
  • 24
  • 46
  • Hello. if i do as you say it will create two columns. generates both 'jobId' and 'jobtypeid_jobtype'. Shouldn't it normally be a single column? – Batu han Nov 26 '22 at 09:40
  • The `JobType` class needs to amend as well for the `JobTables` property. And try to regenerate the `JobTable` table. – Yong Shun Nov 26 '22 at 09:46