我有这个C#方法是asp.net webapi:
public IHttpActionResult Definitions()
{
var words = db.Words
.Where(w => w.Name == "abandon")
.AsNoTracking()
.ToList();
foreach (var word in words)
{
HttpResponse<string> response = Unirest.get("https://wordsapiv1.p.mashape.com/words/" + word.Name)
.header("X-Mashape-Key", "xxx")
.header("Accept", "application/json")
.asJson<string>();
RootObject rootObject = JsonConvert.DeserializeObject<RootObject>(response.Body);
var results = rootObject.results;
foreach (var result in results)
{
if (!(from d in db.WordDefinitions where d.Definition == result.definition select d).Any())
{
var pos = 0;
switch (result.partOfSpeech)
{
case "noun":
pos = 1;
break;
case "verb":
pos = 2;
break;
case "adjective":
pos = 3;
break;
case "Adverb":
pos = 4;
break;
default:
pos = 5;
break;
}
var definition = new WordDefinition()
{
WordId = word.WordId,
Definition = result.definition,
PosId = pos
};
db.WordDefinitions.Add(definition);
}
db.SaveChanges();
}
}
return Ok();
}
代码从头到尾运行。当我在db.SaveChanges()上放置一个断点时,我看到它多次到达那个点,我看到这个定义被填充了。
但是当我检查数据库时,没有添加任何内容。
有没有办法可以添加一些可能会让我知道出错的检查?我怀疑有一个异常,但我认为不是因为代码一直运行到方法结束。
答案 0 :(得分:2)
在将完整列表添加到WordDefinitions之后尝试执行db.SaveChanges。我的意思是在foreach的外部范围之后..更好的是在范围之外有那行代码,因为每次它都会命中db并保存与这样做相比,你的数据相对需要更多的时间......
代码:
public IHttpActionResult Definitions()
{
var words = db.Words
.Where(w => w.Name == "abandon")
.AsNoTracking()
.ToList();
foreach (var word in words)
{
HttpResponse<string> response = Unirest.get("https://wordsapiv1.p.mashape.com/words/" + word.Name)
.header("X-Mashape-Key", "xxx")
.header("Accept", "application/json")
.asJson<string>();
RootObject rootObject = JsonConvert.DeserializeObject<RootObject>(response.Body);
var results = rootObject.results;
foreach (var result in results)
{
if (!(from d in db.WordDefinitions where d.Definition == result.definition select d).Any())
{
var pos = 0;
switch (result.partOfSpeech)
{
case "noun":
pos = 1;
break;
case "verb":
pos = 2;
break;
case "adjective":
pos = 3;
break;
case "Adverb":
pos = 4;
break;
default:
pos = 5;
break;
}
var definition = new WordDefinition()
{
WordId = word.WordId,
Definition = result.definition,
PosId = pos
};
db.WordDefinitions.Add(definition);
}
}
}
db.SaveChanges();
return Ok();
}