I am trying to set up a moq, but i am needing to create a fake IQueryable. i made a Collection but i am at a loss of how to cast that to an IQueryable.
Collection<DetailDataEntity> DetailDataEntityCollection =
new Collection<DetailDataEntity>();
DetailDataEntity DetailDataEntity = new DetailDataEntity();
DetailDataEntity.FeedTypeID = 1;
DetailDataEntityCollection.Add(DetailDataEntity);
_mockRepository.Setup(x => x.GetDetail(It.IsAny<Int32>(),
It.IsAny<Enum.FeedTypeEnum.FeedType>()))
.Returns(DetailDataEntityCollection);
Just call AsQueryable on your collection.
_mockRepository.Setup(x => x.GetDetail(It.IsAny<Int32>(),
It.IsAny<Enum.FeedTypeEnum.FeedType>()))
.Returns(DetailDataEntityCollection.AsQueryable());
I had a simple ICollection object and found that this worked for me:
var tapSettings = xfmrTapSettings.ToList().AsQueryable();
I had to use ToList in front of AsQueryable to make it work.
Related
I have a Mock list like this.
var MockList = new List<Mock>() {
new Mock<IBikeRepository>(MockBehavior.Strict),
new Mock<IGreeterService>(MockBehavior.Strict)
};
Now I get back one object like this.
var greeterServiceMock = this.MockList
.FirstOrDefault(mock => typeof(Mock<IGreeterService>) == mock.GetType());
Since MockList is of the type List<Mock>, the object that I pulled out from the list this.MockList is of the type Mock. But I can see the runtime type is Mock<IGreeterService>
Now I have to cast it to Mock<IGreeterService>
Is there a way here?
Edit
I think I got it.
var t = (Mock<IGreeterService>)greeterServiceMock!;
The ! at the end was the key. It was giving error without it and so I had to put the question here.
The reason you still need to cast is that FirstOrDefault will return a reference of the type of the list. You can filter ans cast at the same time by using OfType:
this.MockList.OfType<Mock<IGreeterService>>().FirstOrDefault();
I would like to make my code convention-based by using Types and keeping things simple, but generics has it's own complexity with it's own learning curve.
I have a bunch of POCOs (Plain Old CLR Objects) in a List that I'd like to iterate through later in the code.
var models = new List<Type>();
models.Add(typeof(Person));
models.Add(typeof(Company));
Would like to cycle through each list item:
models.ForEach(m =>
{
var label = m.FullName;
// var data = JsonConvert.DeserializeObject<List<typeof(m)>>(""); // doesn't work
var data = JsonConvert.DeserializeObject<List<m>>(""); // doesn't work either
...
}
The issue is that the "m" in the Deserialize line isn't working. What would be the best way to pass that through, i.e. making the 'List<m>' a 'List<T>' that we can use?
To use generics, you really need to know the Type (T) at compile time, you don't - you know it at run time. (Caveat: Its possible with reflection, but theres no need to use it when there's an overload as described below)
There is an overload of DeserializeObject which takes a Type rather than use generics. So your code would be
models.ForEach(m =>
{
var label = m.FullName;
var data = JsonConvert.DeserializeObject("",m);
...
}
However, as you've pointed out in comments you actually need a List<T> not a single T. You'll need a little bit of reflection, just to create the right type to pass to the above DeserializeObject call.
var tList = typeof(List<>); // Type of open List
models.ForEach(m =>
{
var label = m.FullName;
var tConvert = = tList.MakeGenericType(m);
var data = JsonConvert.DeserializeObject("",tConvert);
...
}
The answer to your question is above, but the more I look at it the harder it is to see what you can actually do with data. all you'll ever know about data is that it is an object. You cant cast it to anything - you wont know if its a list of Person or a list of Company.
Perhaps this was an overly contrived example you've used for a real-life problem. If not I forsee you're next problem is what to do with data!!
If you don't know the type at compile time you can do this with Reflection. Consider the following code:
models.ForEach(m =>
{
var mi = JsonConvert.GetType()
.GetMethod("DeserializeObject");
var m = mi.MakeGenericMethod(new[] { m });
// you pass [null] for the object because it's a [static] method
// and you don't have to declare [args] if you can express it simply
// but keep in mind that it's simply an object[]
m.Invoke(null, args);
}
Another solution is to call the generic method using reflection (if there isn't any overload that takes the type as parameter)
models.ForEach(m =>
{
MethodInfo method = typeof(JsonConvert).GetMethod("DeserializeObject");
MethodInfo generic = method.MakeGenericMethod(m);
generic.Invoke(null, "");
}
I'm trying to update an entityCollection
Here is my linq:
itemFromDb.MamConfigurationToBrowser_V1 =
(EntityCollection<MamConfigurationToBrowser_V1>) itemFromDb.MamConfigurationToBrowser_V1
.Select(browserEfItem =>
FillFromUi(browserEfItem,
item.MamConfigurationToBrowser_V1
.Single(browserUiItem => browserUiItem.BrowserVersionId == browserEfItem.BrowserVersionId)))
.ToList().AsEnumerable();
However I get a runtime casting error:
Unable to cast object of type
'System.Collections.Generic.List1[Conduit.Mam.MaMDBEntityFramework.MamConfigurationToBrowser_V1]'
to type
'System.Data.Objects.DataClasses.EntityCollection1[Conduit.Mam.MaMDBEntityFramework.MamConfigurationToBrowser_V1]'.
Why is that? As I'm doing linq to entity, no?
You are creating a List<MamConfigurationToBrowser_V1> with your second-last call ToList() in your Linq expression and then you try to cast this list to an EntityCollection<MamConfigurationToBrowser_V1. I would recommend to create a new EntityCollection and add the results from the LINQ query to this collection, like so:
var collection = new EntityCollection<MamConfigurationToBrowser_V1>();
var processedItems = itemFromDb.MamConfigurationToBrowser_V1
.Select(browserEfItem =>
FillFromUi(browserEfItem,
item.MamConfigurationToBrowser_V1
.Single(browserUiItem => browserUiItem.BrowserVersionId == browserEfItem.BrowserVersionId)))
.ToList();
foreach(var item in processedItems)
{
collection.Add(item);
}
Important: your code seems to mix database concerns with business logic and personally I never used an EntityCollect<T> directly in my code. I don't know your context but maybe you should consider using the Repository and Unit of Work pattern. Search for them on Google.
ItemFromDB is an unique object? I mean that if itemFromDB is not a list, yo are trying to convert a unique object to a list.
instead of .ToList().AsEnumerable() you can try to use .FirstOrDefault().
Hoping this is a nice softball of a question for a friday but I have the following line of code:
//System.ArgumentOutOfRangeException generated if there is no matching data
currentAnswers = new CurrentAnswersCollection()
.Where("PARTICIPANT_ID", 10000).Load()[0];
CurrentAnswersCollection is a strongly-typed collection populated by a view going back to my database.
The problem of course is that if there is not a corresponding PARTICIPANT_ID = 10000 I get the error message.
Is there a better way to write this so that I wouldn't get the error message at all?
I just dont know enough about LINQ syntax to know if I can test for the existance first?
thanks.
Use this:
currentAnswers = new CurrentAnswersCollection()
.Where("PARTICIPANT_ID", 10000).Load()
.FirstOrDefault();
It'll return null if there is no first element.
But you may need to fix your code (replicated here) first - the .Where syntax looks dodgy.
The ArgumentOutOfRangeException is occurring when you try to use the indexer to get the first item from the (empty) list. Using the FirstOrDefault() extension method is a convenient way to return the first element of a collection, if there is one, otherwise to return null.
currentAnswers = new CurrentAnswersCollection().Where("PARTICIPANT_ID", 10000)
.Load()
.FirstOrDefault();
http://msdn.microsoft.com/en-us/library/system.linq.enumerable.firstordefault.aspx
Try:
var answers = new CurrenAnswersCollection().Where("PARTICIPANT_ID", 10000);
if(answers.Count() >= 1) currentAnswers = answers.Load()[0];
or something similar.
You need a lambda expression in .Where.
currentAnswers = new CurrentAnswersCollection()
.Where(c => c.PARTICIPANT_ID == 10000).Load().FirstOrDefault();
I have a LINQ statement that returns an anonymous type. I need to get this type to be an ObservableCollection in my Silverlight application. However, the closest I can get it to a
List myObjects;
Can someone tell me how to do this?
ObservableCollection<MyTasks> visibleTasks = e.Result;
var filteredResults = from visibleTask in visibleTasks
select visibleTask;
filteredResults = filteredResults.Where(p => p.DueDate == DateTime.Today);
visibleTasks = filteredResults.ToList(); // This throws a compile time error
How can I go from a anonymous type to an observable collection?
Thank you
As Ekin suggests, you can write a generic method that turns any IEnumerable<T> into an ObservableCollection<T>. This has one significant advantage over creating a new instance of ObservableCollection using constructor - the C# compiler is able to infer the generic type parameter automatically when calling a method, so you don't need to write the type of the elements. This allows you to create a collection of anonymous types, which wouldn't be otherwise possible (e.g. when using a constructor).
One improvement over Ekin's version is to write the method as an extension method. Following the usual naming pattern (such as ToList or ToArray), we can call it ToObservableCollection:
static ObservableCollection<T> ToObservableCollection<T>
(this IEnumerable<T> en) {
return new ObservableCollection<T>(en);
}
Now you can create an observable collection containing anonymous types returned from a LINQ query like this:
var oc =
(from t in visibleTasks
where t.IsSomething == true
select new { Name = t.TaskName, Whatever = t.Foo }
).ToObservableCollection();
Something like this would do the job using type inference features:
private static ObservableCollection<T> CreateObservable<T>(IEnumerable<T> enumerable)
{
return new ObservableCollection<T>(enumerable);
}
static void Main(string[] args)
{
var oc = CreateObservable(args.Where(s => s.Length == 5));
}
You should just be able to do this:
visibleTasks = new ObservableCollection<MyTasks>(filteredResults);
Are you sure that your object is an ObservableCollection indeed? If yes, you can just cast: visibleTasks = (ObservableCollection)filteredResults;
Try:
var filteredResults = from visibleTask in visibleTasks
where(p => p.DueDate == DateTime.Today)
select visibleTask).ToList();
(filteredResults will contain your desired list)