简体   繁体   English

使用外键关联创建现有记录的副本

[英]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. 当使用Add()时,我最终得到两个记录(差异是主键ID),分别在Roles和Progams表中具有相同的Role.Name和Program.Name。

My goal is to have ProfessionalEmploymentRecord p to have an association with a single (unique) Program and Role per record p. 我的目标是让ProfessionalEmploymentRecord p与一个(唯一)程序和每个记录p的角色相关联。

Edit: 编辑:

An Example 一个例子

If I let ProfessionalEmploymentRecord p be p.Role.Name = "Analyst" p.Program.Name= "A" 如果我让ProfessionalEmploymentRecord p为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 然后,Add()函数在ProfessionalEmploymentRecords中创建一个新记录,其中包含RoleId = 2和ProgramId = 2

In the Roles and Programs tables I end up with Roles ID Name 1 Analyst 2 Analyst 在角色和程序表我结束了角色ID名称1名分析员2分析员

Program ID Name 1 A 2 A 程序ID名称1 A 2 A

To simplify the question, why does Add function create entries into two other tables? 为了简化问题,为什么Add函数会在其他两个表中创建条目?

Add a reference of ProfessionalEmploymentRecord in the Program and Role class. 在“程序和角色”类中添加ProfessionalEmploymentRecord的引用。

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; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM