简体   繁体   中英

Creates copy of existing record with foreign key association

I have the following models

public class ProfessionalEmploymentRecord
{
    public int ID { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }

    public virtual Role Role { get; set; }
    public virtual Program Program { get; set; }
}

public class Program
{
    public int ID { get; set; }
    public string Name { get; set; }
}

public class Role
{
    public int ID { get; set; }
    public string Name { get; set; }
}

public ActionResult Add(ProfessionalEmploymentRecord p)
{
    if (ModelState.IsValid)
    {
        //Check which program is being considered
        p.Program.ID = GetProgramId(p.Program.Name);
        p.Role.ID = GetProfessionalId(p.Role.Name);
        db.ProfessionalEmploymentRecords.Add(p);
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(p);
}

When using Add() I end up with two records (difference being the primary key ID) with the same Role.Name and Program.Name in Roles and Progams tables, respectively.

My goal is to have ProfessionalEmploymentRecord p to have an association with a single (unique) Program and Role per record p.

Edit:

An Example

If I let ProfessionalEmploymentRecord p be p.Role.Name = "Analyst" p.Program.Name= "A"

Then the Add() function creates a new record in ProfessionalEmploymentRecords which contains RoleId = 2 and ProgramId = 2

In the Roles and Programs tables I end up with Roles ID Name 1 Analyst 2 Analyst

Program ID Name 1 A 2 A

To simplify the question, why does Add function create entries into two other tables?

Add a reference of ProfessionalEmploymentRecord in the Program and Role class.

public class Program
{
   public int ID { get; set; }
   public string Name { get; set; }
   public virtual ProfessionalEmploymentRecord ProfessionalEmploymentRecord { get; set; }
}

public class Role
{
   public int ID { get; set; }
   public string Name { get; set; }
   public virtual ProfessionalEmploymentRecord ProfessionalEmploymentRecord { 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