Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
like image 549
AyKarsi Avatar asked Nov 10 '11 09:11

AyKarsi


1 Answers

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

like image 111
GrievousAngel Avatar answered Oct 21 '22 19:10

GrievousAngel