views:

97

answers:

2

I want to create a Blog object which has a relation between User. To create the relationship do I have to select User entity first, then set it to User property of Blog object? In Entity Framework samples suggest to set the User object to ViewState and retrieve it when you need to create the relationship, like a basic cache.

Is this necessary? Is there any other way to do this? (like in linq-to-sql setting the foreign keys only without select.)

Here my code sample;

Blog blog = new Blog
            {
                Name = blogName,
                Slogan = slogan,
                User = Entities.Users.First(u => u.Id == userId)
            }

Entities.AddToBlogs(blog);
Entities.SaveChanges();

Edit(To give another chance to question): Is there anything unclear or else?

A: 
Craig Stuntz
Unfortunely, that didn't solve the problem. When I did this, the properties of blog is being tried to added and because of constraints an exception is thrown.
yapiskan
Don't forget step 2!
Craig Stuntz
What is the way of doing that? I could not find any method on DataContext to do it. So I've used AcceptAllChanges().
yapiskan
AcceptAllChanges should do it. Check the Entity state to make sure. As I said, this is speculation on my part; what you're asking isn't officially supported.
Craig Stuntz
I checked it out. But when I tried to add the blog EntityState of the User is became Added and there is no way to set it manually.
yapiskan
OK, we can add that idea to the bin of good ideas that didn't work in real life, then. :(
Craig Stuntz
:/ unfortunately!
yapiskan
+1  A: 

We use the following solution to set foreign keys without retreiving the corresponding entity from the context.

Blog blog = new Blog            
{                
   Name = blogName,                
   Slogan = slogan,                
   UsersReference.EntityKey = new EntityKey("EntityModel.Users", "UserId", userId)            
}

Entities.AddToBlogs(blog);
Entities.SaveChanges();
madC