3

我有一个通过反序列化 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; } }
    }
}

感觉这是重复的,但我没能找到一个好的搜索。

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

4

1 回答 1

0

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

[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]

有关更多信息,请参阅此相关问题

于 2013-08-09T12:30:29.053 回答