[英]How feed a table with multiple foreign keys from different tables
so I have 3 models:所以我有3个模型:
public class Contact
{
public int ContactID { get; set; }
public string name { get; set; }
public int SegmentID { get; set; }
public Segment Segment { get; set; }
}
public class MedicalPlan
{
public int MedicalPlanID { get; set; }
public string name { get; set; }
public int SegmentID { get; set; }
public Segment Segment { get; set; }
}
public class Target
{
public int TargetID { get; set; }
public int MedicalPlanID { get; set; }
public int ContactID { get; set; }
public MedicalPlan MedicalPlan { get; set; }
public Contact Contact { get; set; }
}
A MedicalPlan got many Contacts, and Target got both many MedicalPlans and Contacts,一个 MedicalPlan 有很多联系人,Target 有很多 MedicalPlan 和联系人,
Now Each MedicalPlan has a buttom called generate: Example现在每个 MedicalPlan 都有一个名为 generate 的按钮:示例
What I want is when you press that buttom it creates a Target and generates every Contacts that are associated to that MedicalPlan through SegmentID and insert them in the table Target as shown here我想要的是当您按下该按钮时,它会创建一个目标并生成通过 SegmentID 与该 MedicalPlan 关联的每个联系人,并将它们插入表目标中,如下所示
I've tried something like this:我试过这样的事情:
IEnumurable<int> cons =
from contact in contacts
where contact.SegmentID == planMedical.SegmentID
select contact.ContactID;
int[] res = cons.ToArray();
for ( int j = 0; j < res.Length ; j++)
{
targets.PlanMedicalID = id; //id MedicalPlans current row's key
targets.ContactID = res[j];
_context.Add(targets);
await _context.SaveChangesAsync();
}
But it does nothing..但它什么也没做..
You are creating you ViewModel
which is PlanTargets
, but you have to create you Database
Model Entity, you have to create the object as:您正在创建
ViewModel
,即PlanTargets
,但您必须创建Database
Model 实体,您必须将 object 创建为:
for ( int j = 0; j < res.Length ; j++)
{
var target = new Target //ADD THIS LINE
{
MedicalPlanID = id,
ContactID = res[j]
};
_context.Target.Add(target);
_context.SaveChangesAsync();
}
You are not creating a Target
object, you are creating a PlanTargets
object and trying to add it to your DbContext.您不是在创建
Target
object,而是在创建PlanTargets
object 并尝试将其添加到 DbContext。
NOTE: In your scenerio, you want to create a Target
object for every ContactID
, so in your for loop
you have to create the object with the new
keyword, and set the related properties, after that you have to add it to your DbContext, and when you SaveChanges
then it will save the results to your database.注意:在您的场景中,您想为每个
ContactID
创建一个Target
object ,因此在您的for loop
中,您必须使用new
关键字创建 object 并设置相关属性,之后您必须将其添加到您的 DbContext 中,当您SaveChanges
时,它会将结果保存到您的数据库中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.