简体   繁体   English

检查数据库条目是否存在Entity和Linq

[英]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. 我想说的是,如果找到一个名称为address.City的城市,则不要在数据库中创建一个新的城市。

  • Question is, this syntax isn't good, what's the better way of doing that .Count bit... 问题是,这个语法是不好的,什么是这样做的更好的方法.Count位...

you can do like this by using Any() : 您可以通过使用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.

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