我有以下方法
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);
}
答案 0 :(得分:0)
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();
答案 1 :(得分:0)
查看你的for循环,我不认为错误是因为Artist实体,但它可能是一个不同的实体,因为在for循环的每个步骤中,你在添加Artist后保存上下文但是你有待添加的相册可能会对仍未决定的相册造成严重违规。
好的,我知道了,当你分配艺术家时,你仍然有其他没有ID的专辑,当你向对象上下文添加或附加任何内容时,整个对象图都会被附加。现在问题在于,您正在重复使用之前创建的对象。
在您从rss创建对象的代码中,不要使用实体,而是使用某些代理类。例如RAlbum和RArtist以及你的for循环改变它。
var albums =来自externalSource中的item; 选择新的RAlbum { Country = country //另一个实体,即数据库中存在的实体 Name = item [“Name”]。值, Artist = new RArtist { ExternalId = Int32.Parse(item [“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);
}