0

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?

4

2 回答 2

1

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();
于 2009-08-26T09:59:11.643 回答
0

目前还没有官方支持,但可能会包含在未来的版本中。

但是,您也许可以破解它。我还没有尝试过,但这个想法在概念上似乎是合理的:

  1. 创建一个新用户,并适当地设置 ID。将其附加到对象上下文。
  2. 告诉对象上下文忘记您到目前为止所做的任何更改。
  3. 现在创建一个新博客并将 User 属性设置为您刚刚创建的用户。
  4. 保存对对象上下文的更改。

显然,如果数据库中实际上不存在用户,这将失败。

似乎是个好主意,但似乎行不通。:(

于 2009-01-14T14:11:21.363 回答