【发布时间】:2018-03-31 13:16:12
【问题描述】:
我正在使用实体框架(使用代码优先方法),并且使用预期的外键和唯一键约束成功创建了数据库。
我有这两个模型类:
public class Foo
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
public Bar Bar { get; set; }
}
public class Bar
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
[Index(IsUnique = true), StringLength(512)]
public string Url { get; set; }
}
还有这个应用代码:
var foo = GetData();
using (DatabaseContext db = new DatabaseContext())
{
db.Entry(foo).State = EntityState.Added;
if (foo.Bar != null)
{
var bar = await db.Bar.FirstOrDefaultAsync(x => x.Url == foo.Bar.Url);
if (bar != null)
{
// When I assign an existing entity ...
foo.Bar = bar;
}
}
// ... following exception will be thrown.
await db.SaveChangesAsync();
}
SqlException:无法在具有唯一索引“IX_Url”的对象“dbo.Bar”中插入重复的键行。重复键值为 (https://api.example.com/rest/v1.0/bar/FD6FAB72-DCE2-47DB-885A-424F3D4A70B6)。 声明已终止。
我不明白为什么 Entity Framework 试图添加导航属性 Bar,即使在从同一个 DbContext 获取和分配它之后也是如此。类似的 StackOverflow 问题尚未提供任何可行的解决方案。
如果我需要提供更多信息,请告诉我。
我是否忘记设置任何与 EF 相关的配置或类似的配置?提前谢谢!
【问题讨论】:
标签: c# entity-framework ef-code-first data-annotations navigation-properties