I have been following this Example to implement LazyLoading, to initialize lazyObject with some value i am making a call to function with the help of Lambda Expression. But, i am getting Conversion error and its saying its not delegate. Below is the code:
private Lazy<t_user_audit> lazyList = null;
lazyList = new Lazy<t_user_audit>(() => new t_user_audit { client.GetAudit(10) });
I have searched the error on google, but its does not seems to be helpful and further i have seen this error first time in my life, so might be i am in need of coding help with proper syntax. So can anybody help me now.
public t_user_audit GetAudit(int id)
{
return _work.GetGenericRepositoryFor<t_user_audit>().SingleOrDefault(p => p.CustomerId == id);
}
Now, as you can see i am working in layered architecture, so i won't be able for me to post the whole code and one more thing i am using Entity Framework.
After, using the above line, i get two errors:
Error 17 Cannot convert lambda expression to type 'bool' because it is not a delegate type
And the second is:
Error 18 Cannot initialize type 'BBTI.Entities.t_user_audit' with a collection initializer because it does not implement 'System.Collections.IEnumerable'
New answer with edited question
The problem is that your lambda expression isn't valid - you're trying to use collection initializer syntax, but your type isn't a collection. So instead of this:
() => new t_user_audit { client.GetAudit(10) }
You want:
() => new List<t_user_audit> { client.GetAudit(10) }
Original answer
From the comments:
"it will return an object with single record"
If you mean that GetAudit
is declared to return a t_User
, like this:
public t_User GetAudit(int something)
then that's the problem. To create a Lazy<List<Foo>>
you need a delegate which will return a List<Foo>
, not a single Foo
. So this should work:
lazyList = new Lazy<List<t_User>>(() => new List<t_User> { client.GetAudit(10) });
Or you could make it a Lazy<t_User>
instead, if you're only ever going to fetch a single use.
Another possibility (it's hard to tell as you haven't given enough information in the question) is that GetAudit
returns something like an IEnumerable<t_User>
instead of a List<t_User>
. In that case, you would just need to create a list from the return value:
lazyList = new Lazy<List<t_User>>(() => client.GetAudit(10).ToList());
(I'd also strongly encourage you to start following .NET naming conventions, and ditch the t_
prefix.)
See more on this question at Stackoverflow