One-to many relationship not working - Entity Framework

删除回忆录丶 提交于 2019-12-08 01:57:32

问题


I'm having a problem with creating a one-to-many(or one-to-one?) relationship in entity framework (3.5 I believe).

Example tables/models:

Settings:
    SettingsID pk int not null
    SettingsName varchar(250) null
    SettingsTypeID fk int null

SettingsType:
   SettingsTypeID pk int not null
   SettingsTypeName varchar(250)

I have a foreign key constraint on Settings.SettingsTypeID that references SettingsType.SettingsTypeID.

Upon saving a setting (with a chosen settingstype) the values save correctly (I have checked the DB to be sure and can see the value of Setting.SettingsTypeID update correctly).

However, upon trying to retrieve a settingType object based on the chosen Setting, e.g.

var SettingsType = Setting.SettingsType;

Setting.SettingsType always comes back null?

Am I missing something or?


回答1:


You need to load the SettingType object that is associated with your Setting object, using one of the loading patterns described this article on Loading Related Objects (MSDN).

I'd suggest using the Include method, something like this:

var setting = (from s in context.Settings.Include("SettingsType") 
               where s.SettingsID == id select s).FirstOrDefault();


来源:https://stackoverflow.com/questions/3804923/one-to-many-relationship-not-working-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!