简体   繁体   中英

How can I ensure rows are not loaded twice with EF / LINQ

I created code to load definitions from an external API. The code iterates through a list of words, looks up a definition for each and then I thought to use EF to insert these into my SQL Server database.

However if I run this twice it will load the same definitions the second time. Is there a way that I could make it so that EF does not add the row if it already exists?

public IHttpActionResult LoadDefinitions()
{
    var words = db.Words
        .AsNoTracking()
        .ToList();

    foreach (var word in words)
    {
        HttpResponse<string> response = Unirest.get("https://wordsapiv1.p.mashape.com/words/" + word)
            .header("X-Mashape-Key", "xxxx")
            .header("Accept", "application/json")
            .asJson<string>();

        RootObject rootObject = JsonConvert.DeserializeObject<RootObject>(response.Body);
        var results = rootObject.results;

        foreach (var result in results)
        {
            var definition = new WordDefinition()
            {
                WordId = word.WordId,
                Definition = result.definition
            };
            db.WordDefinitions.Add(definition);
        }
        db.SaveChanges();
    }

    return Ok();
}

Also would appreciate if anyone has any suggestions as to how I could better implement this loading.

You can search for Definition value.

var wd = db.WordDefinition.FirstOrDefault(x => x.Definition == result.definition);
if(wd == null) {
    var definition = new WordDefinition() {
        WordId = word.WordId,
        Definition = result.definition
    };
    db.WordDefinitions.Add(definition);
}

In this way you can get a WordDefinition that already have your value.

If you can also use WordId in the same way:

var wd = db.WordDefinition.FirstOrDefault(x => x.WordId == word.WordId);
foreach (var result in results)
{
    if(!(from d in  db.WordDefinitions where d.Definition == result.definition select d).Any())
    {
        var definition = new WordDefinition()
        {
                WordId = word.WordId,
                Definition = result.definition
        };
        db.WordDefinitions.Add(definition);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM