检查数据库条目是否存在Entity和Linq
本文关键字:Entity Linq 存在 是否 数据库 检查 | 更新日期: 2023-09-27 17:58:30
我有以下回购代码:
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
};
}