gpt4 book ai didi

c# - 将对象图添加到 DbContext

转载 作者:行者123 更新时间:2023-11-30 18:32:54 25 4
gpt4 key购买 nike

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

违反 PRIMARY KEY 约束“PK_dbo.Pickles”。无法在对象“dbo.Pickles”中插入重复键。重复键值为 (P1)。
该语句已终止。

我明白为什么我会得到异常,但没有想到添加图形的好方法。

下面是该问题的小型独立重现。

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; } }
}
}

感觉这是重复的,但我没能找到合适的搜索方式。

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

最佳答案

你要生成你的id,把这个注解放在id上面

[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]

有关更多信息,请参阅此 related question

关于c# - 将对象图添加到 DbContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18144530/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com