简体   繁体   中英

Check if database entry exists Entity and Linq

I have the following repo code:

    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;
    }

I want to say if there is a city found with the name address.City then don't make a new City in the database.. otherwise do.

  • Question is, this syntax isn't good, what's the better way of doing that .Count bit...

you can do like this by using 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
            };
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM