Create new EF object with foreign key reference without loading whole rereference object

雨燕双飞 提交于 2019-12-07 01:52:34

问题


I want to create a new EF object which references another object (the aspnet userId in my example) without loading the foreign (key) object.

So essentially I want to do the following:

buskerSet bs = new buskerSet();
bs.Title = title;
bs.Image = image;
bs.Created = DateTime.Now;
//The following will crash, because bs.aspnet_Users is null
bs.aspnet_Users.UserId = userId;

context.SaveChanges();

In the bs.aspnet_UsersReference I can't find anything that would help..

SOLUTION:

aspnet_Users user = new aspnet_Users { UserId = userId };
context.AttachTo("aspnet_Users", user);
set.aspnet_Users = user;

回答1:


AyKarsi,

Have a look at Alex James EF blog post about using stub objects, it explains how to do what you want.

TIP 26 - How to avoid database queries using Stub Entities

Hope that helps, Nick



来源:https://stackoverflow.com/questions/8077329/create-new-ef-object-with-foreign-key-reference-without-loading-whole-rereferenc

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