EF不检索实体脱离上下文

时间:2016-05-12 10:28:12

标签: c# entity-framework

我想要发生的事情是,如果我已经在会话中创建了记录(GuildName)并将其附加到上下文,那么EF就可以从上下文中检索它而不是创建副本,但它不能使它不会创建重复。

public static async Task ProcessNames()
{
    var db = new SQLDbContext();
    db.Configuration.ProxyCreationEnabled = false;

    var existingNames = db.CharacterNames.Include("GuildName").Include("RealmName").Take(10).ToList();
    var gatherGuildNameTaskList = (
           from name in existingNames 
           select GetGuildFromName(name, db)).ToList();

    await Task.WhenAll(gatherGuildNameTaskList);
    db.SaveChanges();
}


public static async Task GetGuildFromName(CharacterName characterName, SQLDbContext db)
{
    var character = await ApiHelper.GetJsonFromUrlAsync<Character>(new Uri( URL ));
    if (character.Guild == null) return;

    //This is the call that appears to not be working as intended
    var guildName = db.GuildName.
        SingleOrDefault(x => x.RealmName.Name == character.Guild.Name) ?? new GuildName
    {
        Name = character.Guild.Name,
        CharacterNames = new List<CharacterName>(),
        RealmName = characterName.RealmName
    };

    if (!guildName.Equals(characterName.GuildName))
    {
        characterName.GuildName = guildName;
    }
}

我只需要10个名字进行测试,但通常只有几个100k的

我唯一能想到的就是在GetGuildFromName的搜索方法上调用保存更改,但我有一种感觉,它可能无法按预期工作,但可能对性能有害,而不是性能是巨大的因素,但我喜欢尝试让事情合理地发挥作用。

1 个答案:

答案 0 :(得分:0)

我认为你永远不会将newGuildName添加到上下文中(db.GuildName.Add(guildName),如下所示:

var guildName = db.GuildName.
        SingleOrDefault(x => x.RealmName.Name == character.Guild.Name);
if (guildName ==null)
{ 
    guildName = new GuildName
       {
        Name = character.Guild.Name,
        CharacterNames = new List<CharacterName>(),
        RealmName = characterName.RealmName
       };
    db.GuildName.Add(guildName);
}