c# - 为什么要插入倍数?

标签 c# entity-framework

我有以下方法

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 对象,它只设置了 ExternalIdName,但它不是完全连接到我的实体上下文。它是从外部来源抓取的。

当我调用 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/

相关文章:

c# - C# 中的 antlr4 parser.prog

c# - winform 应用程序中的按钮文本

c# - 为什么 "int"和 "sbyte"GetHashCode 函数生成不同的值?

C# Linq 表达式无法翻译

c# - MVC3 将字典值传递给下拉列表并将关联的键绑定(bind)到模型

c# - 图像比较和返回百分比

entity-framework - 在 Entity Framework 6 中的一个事务中删除多行时重复查询

c# - Entity Framework 、存储库模式和 let 语句

unit-testing - Microsoft 的 Entity Framework 如何抑制测试驱动开发?

c# - 如何将复杂的 JSON 对象传递给 ASP.net Controller