简体   繁体   中英

inserting data into tables with foreign keys

I have 2 tables in ms sql server 2008 R2, one of which has foreign key relation to the other

pretty simple:

tableA
prefix nchar(10)
value  nchar(50)

tableB
prefix nchar(10)
value  nchar(50)

ALTER TABLE [dbo].[tableB]  
WITH CHECK ADD  CONSTRAINT [FK_TableA_TableB] FOREIGN KEY([prefix])
REFERENCES [dbo].[TableA] ([prefix])

I fill in data in the tables using the management studio edit table. ensuring each prefix in tableB has a matching prefix in tableA .

Then I import the tables into visual studio C# to create an entity framework model. Everything seem to work fine until I start to reference data in tableA from tableB using the navigation handle, it comes up empty handed.

ie tableB.tableA s come out as null.

Is there a step that needs to be done to update foreign key relations in entity framework and/or ms sql server?

To help others with a similar problem, I am posting what I believe is the solution. Turns out I assumed references were loaded automatically in the Entity Framework. In order to get updated, references need to be explicitly loaded like this

if (!tableB.tableAs.IsLoaded)
    tableB.tableAs.Load();

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