Optional optional parameter

I am using entity 4 infrastructure with edmx and POCOs files in an asp.net mvc application.

First of all, I have a person class that maps to a table in the database.

public class Person { public Int32 ID{get;set;} public string Name{get;set;} public Int32? ParentID{get;set;} } 

Then at my service level, I have the following function to extract all faces. If a parent identifier is provided, the individuals received will be those who have this parent identifier:

 public List<Person> Get(int? parentPersonID = null) { var persons = Repository().GetAll(c => c.ParentID == parentPersonID); } 

Finally, the Repository () function returns an IRepository<Person> , which contains a method:

 public IQueryable<TModel> GetAll(Expression<Func<TModel, bool>> predicate = null) { var result = ObjectSet.AsQuaryable(); //ObjectSet is a ObjectSet<Person> instance if (predicate != null) result = result.Where(predicate); return result; } 

Now the problem is that if I pass null as parentPersonID to the service level, then Get(null) . Enumeration does not produce any results. However, if I change the service level code to:

 public List<Person> Get(int? parentPersonID = null) { var persons = Repository().GetAll(null); } 

everything works as expected.

Any ideas why this is?

EDIT : If I replaced the functional level code as follows:

 var persons = Repository().GetAll(c => c.ParentID.Equals(parentPersonID)); 

instead:

 var persons = Repository().GetAll(c => c.ParentID == parentPersonID); 

It works as expected - the first row retrieves records from the database, and the second does not. I'm still curious to know what the difference is in Equals() and == in this case.

+3
source share
1 answer

I suspect this is due to how equality is handled. Try the following:

 public List<Person> Get(int? parentPersonID = null) { var persons = Repository().GetAll(parentPersonID == null ? c => !c.ParentID.HasValue : c => c.ParentID == parentPersonID); ... } 

This will change the predicate to explicitly invalidate when passing to parentPersonID from null , instead of just matching what you passed. There may be a more elegant way of expressing this, but at least try to start it.

(I assume that if you specify parentPersonID of null , you want all people with zero parentPersonID , not just all people ... that would be a different change.)

+2
source

Source: https://habr.com/ru/post/944003/


All Articles