实体框架code首先AddOrUpdate方法插入重复的值 [英] Entity Framework Code First AddOrUpdate method insert Duplicate values
问题描述
我有简单的实体:
public class Hall
{
[Key]
public int Id {get; set;}
public string Name [get; set;}
}
然后在种子
方法我用 AddOrUpdate
来填充表:
var hall1 = new Hall { Name = "French" };
var hall2 = new Hall { Name = "German" };
var hall3 = new Hall { Name = "Japanese" };
context.Halls.AddOrUpdate(
h => h.Name,
hall1,
hall2,
hall3
);
然后,我在包管理控制台运行:
Then I run in the Package Management Console:
Add-Migration Current
Update-Database
这是所有罚款:我的表格大厅有三行。但是,如果我在包管理控制台运行更新 - 数据库
再次我已经有五排:
Id Name
1 French
2 Japaneese
3 German
4 French
5 Japanese
为什么呢?我认为这是应该重新三人行,不是五个。我试图用编号
属性,而不是名称
,但它不赚取差价。
Why? I think it is should be three rows again, not five. I tried to use Id
property instead of Name
but it does not make the difference.
更新:
这code产生相同的结果:
This code produces the same result:
var hall1 = new Hall { Id = 1, Name = "French" };
var hall2 = new Hall { Id = 2, Name = "German" };
var hall3 = new Hall { Id = 3, Name = "Japanese" };
context.Halls.AddOrUpdate(
h => h.Id,
hall1);
context.Halls.AddOrUpdate(
h => h.Id,
hall2);
context.Halls.AddOrUpdate(
h => h.Id,
hall3);
我也有通过的NuGet安装了最新的EntityFramework。
Also I have the latest EntityFramework installed via nuget.
推荐答案
好吧,我撞了我的脸离开键盘与此一个小时。如果您的表的ID字段是一个标识字段,那么它不会工作,所以使用不同的一个identifierEx pression。我使用的名称属性,并且还从新馆{...}
初始化删除ID字段。
Ok I was banging my face off the keyboard for an hour with this. If your table's Id field is an Identity field then it won't work so use a different one for identifierExpression. I used the Name property and also removed the Id field from the new Hall {...}
initializer.
这种调整到OPS code为我工作,所以我希望它可以帮助别人:
This tweak to the OPs code worked for me so I hope it helps someone:
protected override void Seed(HallContext context)
{
context.Halls.AddOrUpdate(
h => h.Name, // Use Name (or some other unique field) instead of Id
new Hall
{
Name = "Hall 1"
},
new Hall
{
Name = "Hall 2"
});
context.SaveChanges();
}
这篇关于实体框架code首先AddOrUpdate方法插入重复的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!