M
M
Michael2016-06-08 15:14:14
C++ / C#
Michael, 2016-06-08 15:14:14

Why is Entity Framework creating the wrong query?

Good afternoon!
There is an essence

public partial class countries
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public countries()
        {
            this.people = new HashSet<people>();
        }
    
        public int id { get; set; }
        public string full_name { get; set; }
        public string name { get; set; }
        public string full_name_eng { get; set; }
        public string name_eng { get; set; }
        public string iso_num { get; set; }
        public string iso2 { get; set; }
        public string iso3 { get; set; }
    
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<people> people { get; set; }
    }

I made a method in the repository
public countries FindFirst(Func<countries, bool> predicate)
        {
            return db.countries.FirstOrDefault(predicate);
        }

Calling a method from code
public bool CountryExist(int iso)
        {
            var result = db.Countries.FindFirst(c=>c.iso_num == iso.ToString());
            return result != null ? true : false;
        }

Why does EF create a query without imposing a WHERE clause?
SELECT * FROM countries

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Lastochkin, 2016-06-08
@Slider_vm

Read about the difference between IEnumerable<> and IQuerable<>

public countries FindFirst(Expression<Func<countries, bool>> predicate)
{
...      
}

CountryExist() is best rewritten like this:
public bool CountryExist(int iso)
{
    var isoNum = iso.ToString();
    return db.Countries.Any(c=>c.iso_num == isoNum);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question