Create a new EF object with a foreign key reference without loading the entire rewrite object

I want to create a new EF object that references another object (aspnet userId in my example) without loading an external (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 bs.aspnet_UsersReference I can not find anything that could help.

DECISION:

aspnet_Users user = new aspnet_Users { UserId = userId };
context.AttachTo("aspnet_Users", user);
set.aspnet_Users = user;
+5
source share
1 answer

AyKarsi,

Take a look at the blog post by Alex James EF on the use of stub objects that explains how to do what you want.

TIP 26 - Avoiding Database Queries Using Stub Objects

Hope this helps, Nick

+6
source

All Articles