为什么要尝试插入倍数
本文关键字:插入 为什么 | 更新日期: 2023-09-27 18:12:15
我有以下方法
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();
看看你的for循环,我不认为错误是因为艺术家实体,但它可能是一个不同的实体,因为在for循环的每一步中,你在添加艺术家后保存上下文,但你有挂起的添加专辑,它可能有键违反的专辑,仍然挂起。
好的,我明白了,当你分配艺术家时,你还有其他没有id的专辑当你添加或附加任何东西到对象上下文时,整个对象图被附加。现在的问题是,您正在重用以前创建的对象。
在你的代码中,当你从rss中创建对象时,不要使用实体,而是使用一些代理类。例如RAlbum和RArtist,并在For循环中更改它。var albums = from item in externalSource;select new RAlbum {Country = Country//另一个实体,存在于数据库中的实体Name = item["Name"]。值,Artist = new RArtist { ExternalId = Int32.Parse(项目("ArtistId")value),Name = item["ArtistName"]。价值 } };
public static Artist ProcessArtist(RArtist 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;
}
foreach (var album in albums) {
Album a = new Album();
// copy properties of a from album
a.Artist = ProcessArtist(album.Artist, db);
db.Album.AddObject(a);
}