简体   繁体   中英

Passing lazy function as parameter

last few days I'm trying to find a way how to achieve this king of result. I have Entity Framework function

_context.Playlists.Find(playlistId)

Playlists - is my Entity Dbset.

Find() - Finds an entity with the given primary key values if found, is attached to the context and returned. If no entity is found in the context or the store, then null is returned.

playlistId - Playlist ID that I'm looking for.

Of course I could check it in every function, but I got a lot of this functions where I use Find() with various Entities so I want to keep code clean without repeating logic.

I want to write a function that will check if it's null or not. So basically what I want to do is:

MethodToCheckIfNotNull(_context.Playlists.Find(playlistId));

So if it's null it will throw an exception and if it's not null it will return Entity. Could anybody provide an example how can I achieve this?

As far as I understand, you're looking for generic method like this one:

public T MethodToCheckIfNotNull<T>(Func<T> function) where T : class {
 var entity = function();
 if(entity == null) throw new MyException();
 return entity;
}

This method accepts generic Func which it can execute in a lazy way.

use:

var notNull = MethodToCheckIfNotNull(() => _context.Playlists.Find(playlistId));

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