简体   繁体   中英

How feed a table with multiple foreign keys from different tables

so I have 3 models:

 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,

Now Each MedicalPlan has a buttom called generate: Example

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

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:

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.

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.

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