c# - EF - 如果使用实体对象,则重新插入外键

标签 c# entity-framework entity-framework-6

因此,当我创建对象时,EF 遇到了这个问题,该对象对从数据库检索但来自不同数据库上下文的另一个对象具有 FK 引用(请参阅 GetBlog 方法)。问题是,每当我尝试将此 FK 引用与主对象一起插入时,都会重新创建 FK 引用。

一个解决方案是我可以使用 FK 对象的 ID,这很有效,但我想知道是否可以使用整个对象进行插入,如下例所示,而无需复制 FK 对象。

我尝试了 db.Blogs.Attach(fkBlog) 但没有帮助。也没有将对象状态设置为已添加/未更改。有什么想法吗?

    public static void Main(string[] args)
    {
        using( var db = new BloggingContext() )
        {
            for( int i = 0; i < 10; ++i )
            { 
                var blog = new Blog() { Name = i.ToString(), Description = "Desc", Url = String.Format( "http://{0}", i ) };

                db.Blogs.Add(blog);
                db.SaveChanges();
            }

            for( int i = 0; i < 10; ++i )
            { 
                var fkBlog = GetBlog();

                var post = new Post()
                {
                    Blog = fkBlog,
                    Content = String.Format("Blog Content {0}", i),
                    Title = String.Format("Blog Title {0}", i)
                };

                db.Posts.Add(post);
                db.SaveChanges();
            }
        }
    }

    public static Blog GetBlog()
    {
        using( var db = new BloggingContext() )
        {
            return db.Blogs.OrderBy( x=>Guid.NewGuid() ).FirstOrDefault();
        }
    }

如果我使用 attach 方法(就在实体加载下),我会收到以下错误:

Attaching an entity of type '...Blog' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.

Edit2:附加实际上失败了,因为我试图在 for 循环内附加对象。如果我只附加每个博客一次,或者如果我总是在保存所有作品后删除该对象。

不幸的是,在我的情况下,内联不是一个选项。我依赖于外部数据提供者。

最佳答案

您应该使用相同的上下文对象:

public static void Main(string[] args)
{
    using( var db = new BloggingContext() )
    {
        for( int i = 0; i < 10; ++i )
        { 
            var blog = new Blog() { Name = i.ToString(), Description = "Desc", Url = String.Format( "http://{0}", i ) };

            db.Blogs.Add(blog);
            db.SaveChanges();
        }

        for( int i = 0; i < 10; ++i )
        { 
            var fkBlog = db.Blogs.OrderBy( x=>Guid.NewGuid() ).FirstOrDefault();

            var post = new Post()
            {
                Blog = fkBlog,
                Content = String.Format("Blog Content {0}", i),
                Title = String.Format("Blog Title {0}", i)
            };

            db.Posts.Add(post);
            db.SaveChanges();
        }
    }
}

或者为两个操作创建两个完全独立的Context:

public static void Main(string[] args)
{
    using( var db = new BloggingContext() )
    {
        for( int i = 0; i < 10; ++i )
        { 
            var blog = new Blog() { Name = i.ToString(), Description = "Desc", Url = String.Format( "http://{0}", i ) };

            db.Blogs.Add(blog);
            db.SaveChanges();
        }
    }

    using( var db = new BloggingContext() )
    {
        for( int i = 0; i < 10; ++i )
        { 
            var fkBlog = GetBlog();
            db.Context.Attach(fkBlog);

            var post = new Post()
            {
                Blog = fkBlog,
                Content = String.Format("Blog Content {0}", i),
                Title = String.Format("Blog Title {0}", i)
            };

            db.Posts.Add(post);
            db.SaveChanges();
        }
    }
}

关于c# - EF - 如果使用实体对象,则重新插入外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30171878/

相关文章:

c# - 如何通过非主键创建一对一关系(EF First Code)

c# - AWS RSD - C# .Net 核心 Entity Framework - 创建表 - 访问被拒绝

timezone - MVC 处理时区和 JSON 序列化 - 如何转换为特定时区

c# - Entity Framework : Eager loading with excludes instead of includes?

c# - 正确使用 phantomJS 和代理

c# - 在 Response.Redirect() 之后,代码继续执行

c# - EF Code First INSERT 语句与 FOREIGN KEY 约束冲突

C# 动态方法 : return string representation of integer

c# - Entity Framework 的悲观并发

entity-framework - base.OnModelCreating(modelBuilder) 是必要的吗?