[英]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.