我有以下回购代码:
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
位的更好方法是什么...... 答案 0 :(得分:4)
你可以使用 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
};
}