简体   繁体   English

使用外键将数据插入表中

[英]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 我在ms sql server 2008 R2中有2个表,其中一个表与另一个表有外键关系

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 . 确保每个前缀tableB有一个前缀匹配tableA

Then I import the tables into visual studio C# to create an entity framework model. 然后我将表导入visual studio C#以创建实体框架模型。 Everything seem to work fine until I start to reference data in tableA from tableB using the navigation handle, it comes up empty handed. 一切似乎工作正常,直到我开始使用导航句柄从tableB引用tableA数据,它空出来了。

ie tableB.tableA s come out as null. tableB.tableA s为null。

Is there a step that needs to be done to update foreign key relations in entity framework and/or ms sql server? 是否需要在实体框架和/或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. 事实证明我假设引用是在Entity Framework中自动加载的。 In order to get updated, references need to be explicitly loaded like this 为了获得更新,需要像这样显式加载引用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM