简体   繁体   中英

Entity Framework not writing to Junction Table

This is the first real application that I have created so please be gentile.

Database contains a table named APN with primary key APNID, another table BGP with primary key BGPID. Junction table named APNBGP with two columns acting as composite key made up of the two Foreign Keys: APNID, BGPID. The model.edmx file does show a many-to-many association between the APN and BGP tables.

APN vtcApn = new APN();
BGP vtcBGP = new BGP();

vtcVlan.VlanID = Convert.ToInt32(ddVlans.SelectedValue);
vtcApn.APN_Name = apnName.Text;
vtcApn.PDP = PDP.Text;

vtcBGP.RemotePeer = vtcPriPeer.Text;
vtcBGP.RemoteAS = vtcPriAs.Text;

dbContext.APNs.AddObject(vtcApn);
dbContext.BGPs.AddObject(vtcBGP);
dbContext.SaveChanges();

When I run the application it saves all the APN and BGP properties to the database but it does not update the APNBGP junction table. It was my understanding that EF would take care of updating all the affected tables. Thanks in advance!

Yes. Tell me. Where, exactly, did you tell EF that your APN and BGP were related? You didn't.

You would typically have some sort of collection on each. For instance, you may have a BGPs collection on your APN entity. You would then do something like this:

vtcApn.BGPs.Add(vtcBGP);

You would not then have to add it to the dbContext.BGPs.

use Add() method instead of AddObject() as mentioned below:

dbContext.APNs.Add(vtcApn);
dbContext.BGPs.Add(vtcBGP);
dbContext.SaveChanges();

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