我有一个数据库,我希望它的一部分(名称)不被复制。我试图检查它是否存在,如果不存在则不保存此部分,但无论它是否已经存在,它都会保存。
代码:
var reviewSubject = from c in db.Subject select
c.SubjectName.ToString().ToLower();
var match = reviewSubject.FirstOrDefaultAsync(stringToCheck => stringToCheck.Equals(model.sub.SubjectName.ToLower()));
model.rev.Created = DateTime.Now;
if (ModelState.IsValid)
{
if ((model.sub.SubjectName.ToLower()).Equals(match))
{
//Do nothing
}
else
{
model.sub.GBU = model.rev.GBU;
db.Subject.Add(model.sub);
}
}
答案 0 :(得分:1)
您没有在reviewSubject.FirstOrDefaultAsync
的结果中使用await关键字,而Task<T>
会返回var match = await reviewSubject.FirstOrDefaultAsync(stringToCheck => stringToCheck.Equals(model.sub.SubjectName.ToLower()));`
。因此,您正在检查任务是否等于字符串,这是错误的。
正确的用法是:
var match = reviewSubject.FirstOrDefault(stringToCheck => stringToCheck.Equals(model.sub.SubjectName.ToLower()));`
如果您不想使用async方法,可以使用同步方法:
public stream Get()
{
if(WebOperationContext.Current.IncomingRequest.Headers.AllKeys.Contains("Authorization"))
{
//Validating the header
...
if( valid header)
{
WebOperationContext.Current.OutgoingResponse.ContentType = "application/xml";
byte[] bytes = Encoding.UTF8.GetBytes(xml);
var stream = new MemoryStream(bytes);
stream.Seek(0, SeekOrigin.Begin);
return stream;
}
if(invalid header)
{
//I need to generate no response codes from here.
//I tried, throw exception, change status code, return null stream but nothing worked.
}
}
}