我有以下方法
public static Artist ProcessArtist(Artist artist, Entities db) {
var artistLookup = db.Artist.SingleOrDefault(x => x.ExternalId == artist.ExternalId);
if (artistLookup == null) {
artistLookup = new Artist {
ExternalId = artist.ExternalId,
Name = artist.Name
};
db.Artist.AddObject(artistLookup);
db.SaveChanges();
}
return artistLookup;
}
我使用它的方式是传入一个 Artist
对象,它只设置了 ExternalId
和 Name
,但它不是完全连接到我的实体上下文。它是从外部来源抓取的。
当我调用 db.SaveChanges()
时,它会抛出错误,说我已经破坏了 ExternalId
的唯一键约束。我不知道它会如何尝试插入倍数。
有没有人有什么见解?谢谢!
编辑:我在下面添加了我的调用代码
var albums = from item in externalSource
select new Album {
Country = country // Another entity, one that exists in the database
Name = item["Name"].Value,
Artist = new Artist {
ExternalId = Int32.Parse(item["ArtistId"].Value),
Name = item["ArtistName"].Value
}
};
然后我为每张专辑调用 ProcessArtist
foreach (var album in albums) {
album.Artist = ProcessArtist(album.Artist, db);
db.Album.AddObject(album);
}
最佳答案
var artistLookup = db.Artist.SingleOrDefault(x => x.ExternalId == artist.ExternalId);
//in this line you get an artist from the database
//i dont know why would you want to insert the artist that you just get from the database
//you are reinserting an existing record. That's the reason you get the error
db.Artist.AddObject(artistLookup);
db.SaveChanges();
关于c# - 为什么要插入倍数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7871017/