如何使用 EF4 Code-First 同时创建两个关联实体

发布于 2024-10-18 00:08:20 字数 985 浏览 0 评论 0原文

假设我有 2 个实体,PostPostHistory。每当我创建或编辑帖子时,我都想创建它的精确副本作为 PostHistory 来记录对帖子所做的所有更改。假设帖子实体具有以下定义:

public class Post
{
    public int Id { get; set; }
    public string Text { get; set; }
    public virtual ICollection<PostHistory> PostHistory{ get; set; }
}

当我创建第一个 Post 时,问题就出现了。例如,如果我尝试这样做:

Post post = new Post { Text = "Blah" };
context.Posts.Add(post);
PostHistory history = new PostHistory { Text = "Blah"};
context.PostHistory.Add(history);
post.PostHistory.Add(history);

那将会失败,因为 posthistory 都是新实体,因此 Post.PostHistory 为 null尚未初始化。我能看到做到这一点的唯一方法是首先将 post 提交到数据库,然后将 history 提交到数据库,但我不明白为什么要执行 2 个单独的插入为此应该是必要的。

如果我有一个将 ICollection 初始化为 List 的构造函数,一切正常,但强制实现 List 会导致其他问题,并且几乎没有代码优先教程会执行此强制启动。

那么处理这种情况的最佳方法是什么?

So Say I have 2 entities, Post and PostHistory. Whenever I create or edit a post, I want to create an exact copy of it as PostHistory to log all changes made to a post. Say the post entity has the following definition:

public class Post
{
    public int Id { get; set; }
    public string Text { get; set; }
    public virtual ICollection<PostHistory> PostHistory{ get; set; }
}

The problem comes when I create my first Post. For example, if I try this:

Post post = new Post { Text = "Blah" };
context.Posts.Add(post);
PostHistory history = new PostHistory { Text = "Blah"};
context.PostHistory.Add(history);
post.PostHistory.Add(history);

That will fail because since both post and history are new entities, Post.PostHistory is null due to it not having been initialized yet. The only way I can see to do this is to first commit post to the db, then commit history to the database, but I don't see why performing 2 separate inserts should be necessary for this.

If I have a constructor that initializes the ICollection to a List<T> everything works fine, but forcing the implementation to List<T> causes other issues, and almost no code-first tutorials do this forced initiation.

So what's the best way to handle this situation?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

空心↖ 2024-10-25 00:08:20

您可以在客户端代码本身中初始化列表:

Post post = new Post 
{ 
    Text = "Blah" 
    PostHistory = new List() 
    { 
        new PostHistory { Text = "Blah" }
    }
};        
context.Posts.Add(post);
context.SaveChanges();

但是,在构造函数内初始化集合没有任何问题,实际上建议这样做,因为它使您不必在所有客户端代码中初始化它。

You can initialize the list in the client code itself:

Post post = new Post 
{ 
    Text = "Blah" 
    PostHistory = new List() 
    { 
        new PostHistory { Text = "Blah" }
    }
};        
context.Posts.Add(post);
context.SaveChanges();

However, there is nothing wrong with initializing the collection inside the constructor and it is actually recommended because it saves you from having to initialize it in all the client codes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文