![](/img/trans.png)
[英]Efficiently check if record exists in database using Entity framework LINQ
[英]Check if database entry exists Entity and Linq
我有以下回購代碼:
public int Create(Address address)
{
context.Addresses.Add(address);
int dbCity = context.Cities.Select(c => c.Name == address.City).Count();
if( dbCity == 0 )
{
City newCity = new City
{
Name = address.City
};
context.Cities.Add(newCity);
}
context.SaveChanges();
return address.AddressID;
}
我想說的是,如果找到一個名稱為address.City
的城市,則不要在數據庫中創建一個新的城市。
.Count
位... 您可以通過使用Any()來做到這一點:
bool flag = context.Cities.Any(c => c.Name == address.City);
if(!flag)
{
// no city exists with this name
City newCity = new City
{
Name = address.City
};
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.