将对象图添加到DbContext

时间:2013-08-09 10:21:42

标签: c# entity-framework ef-code-first dbcontext

我有一个对象图是通过反序列化json创建的,当我调用SaveChanges时我得到了:

Violation of PRIMARY KEY constraint 'PK_dbo.Pickles'. Cannot insert duplicate key in object 'dbo.Pickles'. The duplicate key value is (P1). The statement has been terminated.

我理解为什么我会得到异常但却没有想到添加图形的好方法。

以下是该问题的一个小型独立复制品。

using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using NUnit.Framework;

namespace Tempy
{
    public class DbTests
    {
        private Unicorn _u1 = new Unicorn { Id = "U1" };
        private Unicorn _u2 = new Unicorn { Id = "U2" };
        private Pickle _p1 = new Pickle { Id = "P1" };
        private Pickle _p2 = new Pickle { Id = "P2" };


        [SetUp]
        public void SetUp()
        {
            using (var context = new TempContext())
            {
                if (context.Database.Exists())
                    context.Database.Delete();
                context.Database.CreateIfNotExists();
            }
        }

        [Test]
        public void InsertTest()
        {
            _u1.Pickles.UnionWith(new[] { _p1, _p2 });
            _u2.Pickles.UnionWith(new[] { _p1, _p2 });
            using (var context = new TempContext())
            {
                context.Unicorns.Add(_u1);
                context.Unicorns.Add(_u2);
                context.SaveChanges();
            }
        }

        [Test]
        public void InsertFailsTest()
        {
            _u1.Pickles.UnionWith(new[] { _p1, _p2 });
            _u2.Pickles.UnionWith(new[] { new Pickle { Id = _p1.Id }, _p2 });
            using (var context = new TempContext())
            {
                context.Unicorns.Add(_u1);
                context.Unicorns.Add(_u2);
                Assert.Throws<DbUpdateException>(()=>context.SaveChanges()); //Is there a nice way to get this to work?
            }
        }
    }
    public class TempContext : DbContext
    {
        public DbSet<Pickle> Pickles { get; set; }
        public DbSet<Unicorn> Unicorns { get; set; }
    }

    public class Pickle
    {
        public string Id { get; set; }

        private readonly ISet<Unicorn> _unicorns = new HashSet<Unicorn>();
        public virtual ISet<Unicorn> Unicorns { get { return _unicorns; } }
    }

    public class Unicorn
    {
        public string Id { get; set; }

        private readonly ISet<Pickle> _pickles = new HashSet<Pickle>();
        public virtual ISet<Pickle> Pickles { get { return _pickles; } }
    }
}

这样的感觉是重复的,但我没有想出一个好的搜索。

问题:添加此图表的好方法是什么?

1 个答案:

答案 0 :(得分:0)

您必须生成您的ID,将此注释放在ID

上方
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]

了解更多信息,请参阅此related question