当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - 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();
分享给朋友:
您可能感兴趣的文章:
随机阅读: