In order to test a method that uses a stored procedure, a fake method has been created. This method is to return a list of ints.
Something like this ...
public virtual ObjectResult<Nullable<int>> available_IDs( ... )
{
List<int?> fakeAvailableIDList = new List<int?>();
fakeAvailableIDList.Add(1);
fakeAvailableIDList.Add(2);
fakeAvailableIDList.Add(3);
ObjectResult<Nullable<int>> result = fakeAvailableIDList.All(m => m > 0);
return result;
}
which fails with
Cannot implicitly convert type 'bool' to 'System.Data.Objects.ObjectResult<int?>'
tried (amoungst other things)
ObjectResult<Nullable<int>> result = fakeAvailableIDList.All(m => m > 0);
which gives
Cannot implicitly convert type 'System.Collections.Generic.List<int?>' to 'System.Data.Objects.ObjectResult<int?>'
how can I get a List<> into ObjectResult ?
The line
fakeAvailableIDList.All(m => m > 0);
returns a boolean because .All returns True or False depending on whether or not all elements in the collection meet the specified condition.
So, a variable of type ObjectResult can't be set to a variable of type Bool.
The ObjectResult and ObjectResult<T> types have hidden constructors, which means you can't create instances at will. Also, the ObjectResult<T> type is sealed, which means it can't be extended. So, you might be out of luck if you're looking for an easy way to create an ObjectResult from an Enumerable.
The easiest thing to do, I think, would be to change the type used by the method you're trying to test. So, if that method has the signature:
void Foo(ObjectResult<int?> result);
Change it to:
void Foo(IEnumerable<int?> result);
That will allow you to create a fake collection with which the method can be tested, and you'll still be able to pass the method an ObjectContext<int?> type because ObjectContext<int?> extends IEnumerable<int?>.
I realize this has already been answered, but a solution I have come up with is to mock the specific Linq extension off of ObjectResult<T>.
For example:
Mock.Get(PortalEntitiesMock).Setup(m => m.ExecuteSqlQuery(It.Is<String>(x => x.ToUpper().StartsWith("SELECT"))).FirstOrDefault()).Returns<string>(p=>p).Verifiable();
So, you can mock individual items on a ObjectResult<T> object if not the actual ObjectResult<T>.
Related
I am trying to make a function that generically retrieves data from my MongoDB collections. To do this I have constructed a generic method that returns a List<T>.
My issue is that I have to create this List<T> to return, but I do so based on the typeof T. I am not sure what I need to do to please the compiler..
public async Task<List<T>> GetDocsAsync<T>(
CollectionTypes collection, // Enum representing my Collections
FilterDefinition<BsonDocument> search,
SortDefinition<BsonDocument> sort = null)
{
// Get BsonDocuments from the collection based on the search and sort criteria
List<BsonDocument> matchedDocs;
IMongoCollection<BsonDocument> MongoCollection = GetCollection(collection);
if (sort == null) matchedDocs = await MongoCollection.Find(search).ToListAsync();
else matchedDocs = await MongoCollection.Find(search).Sort(sort).ToListAsync();
// Return a List<T>, covert matchedDocs to List<T> if need be
Type docType = typeof(T);
if (docType == typeof(BsonDocument))
return matchedDocs;
else if (docType == typeof(LogEvent_DBDoc))
return LogEvent_DBDoc.ConvertFromBson(matchedDocs);
// ...
}
At both of the return lines I receive an error along the lines of "Cannot implicitly convert from List<[KnownType]> to List<T>. Which makes sense to me, because the typeof T does not necessarily match the typeof say BsonDocument. But I have made the proper check to do so.
Can I cast List<[KnownType]> to List<T>?
You are abusing generic syntax. Generic code should be generic, i.e. work with whatever type you use.
You should have different methods, depending on the type that will be passed in. By all means, make the truly generic parts into its own generic method, which your type-specific methods can call. But have the caller, who already knows what type it's using, pick the appropriate method based on that type, and then just use that type explicitly in each type-specific method.
It's hard to say with the example you have, but if you can provide a good Minimal, Complete, and Verifiable example that shows clearly what you're doing, I would be happy to refactor it to show what I mean.
If you're sure you have the List<KnownType> that matches the type of current generic instantiation of List<T> you can cast it to the required generic type with the help of intermediate cast to object:
List<T> GetListOf<T>() {
if (typeof(T) == typeof(String)) {
var stringList = new List<String> { "a", "b" };
return (List<T>)(object)stringList;
}
throw new NotSupportedException();
}
Leaving the moral judgement whether you should do so to yourself )
This question was completely edited. To see the original one, see the edit history
I think I should explain a little bit of my situation and context of the problem.
I'm inspecting a type for a property annotated with a custom attribute. I then get the value of that property, but as an object:
IEnumerable<object> propertiesValues = myType.GetProperties().Where(p => p.GetCustomAttributes(typeof(MyCustomAttribute)) != null);
Once I have these values I want to call my method Map on them, which converts them to a different object depending on their type. This is because my database API requires so.
foreach(object value in propertiesValues)
{
object mapped = Map(value);
// ...
}
I need all IEnumerable<NumberType> values, to be converted to IEnumerable<string>. So my first approach was:
public static object Map(object value)
{
if(value is IEnumerable<short> || value is IEnumerable<int> || ....)
return ((IEnumerable<object>) value).Cast<string>();
}
However, this is throwing a runtime exception, as I cannot cast IEnumerable<int> to IEnumerable<object> for example.
The feature you want is called covariance, and C# supports it on IEnumerable<T> only when the type arguments are both reference types. That is, IEnumerable<string> may be converted to IEnumerable<object>, but IEnumerable<int> may not be so converted.
The reason is: when you get a sequence of strings, those string references are already legal object references. But an int only becomes a legal object reference when it is boxed; where does the compiler know to insert the boxing operation? It doesn't, so the conversion is illegal.
To convert an IEnumerable<int> to IEnumerable<object> you have to do the boxing explicitly via a projection:
from number in items select (object)item
or
items.Select(item => (object) item)
That will be IEnumerable<object>, and you can then do what you like to that.
Or use the Cast sequence operator
items.Cast<object>()
which does the same thing. Or use its query form:
from object item in items select item
Or simply use the non-generic IEnumerable, which gives you a sequence of boxed values if in fact it is a sequence of structs.
I note though that your plan of then casting IEnumerable<object> to IEnumerable<string> via the Cast extension method is doomed to failure. Those items will be boxed ints. Boxed ints cannot be unboxed to string.
It seems like you are fighting the type system here instead of working with it. Perhaps you should describe your real problem, rather than your attempts to do an end-run around the type system to solve it.
Why don't you do this
var source = ... /// IEnumerable<???>
var destination = source.Select(item => item.ToString());
You could update Map's signature as well:
object Map<TItem, TSource>(TSource source)
: where TSource : IEnumerable<TItem>
or
object Map<TItem>(IEnumerable<TItem> source)
I am sure the answer to this is quite simple but I am trying to write an if statement (C# 5.0) to determine whether or not an anonymous type is empty or not. Here is a simplified version of my code:
public void DoSomething(object attributes)
{
// This is the line I need??
if (atrributes != new {}) {
}
}
The attributes variable gets created dynamically depending on what is needed and sometimes it is empty.
So how do I determine if an anonymous type is empty?
Anonymous types do not provide operator overloads for ==, although it wouldn't matter in this case since one of the arguments is typed object. However the C# compiler does provide Equals, GetHashCode, and ToString implementations.
Use the static object.Equals, method which will do the appropriate null checks and then call the virtual Equals method on the first argument:
object.Equals(attributes, new { });
You could also cache a static instance if you were concerned about the overhead of an allocation for each comparison.
If by empty you mean no properties, you can use reflection:
var o1 = new {};
o1.GetType().GetProperties().Count(); //==0
var o2 = new {test=1};
o2.GetType().GetProperties().Count(); //==1
I have a quick question.
I have a few classes, say Class SubA, SubB and SubC.
I also have an abstract class, lets say Parent
So I have an array of Parent objects, which contains instances of SubA, SubB and SubC.
I am basically trying to loop through the array or Parents and get a particular instance of SubA.
I have trieed the following but it produces a type exception:
foreach (SubA a in Parent.GetList())
any help would be greatly appreciated.
Yes, that current code has an implicit cast, which will fail if you've got an object of the "wrong" type in your collection. I suggest you use LINQ's OfType method:
using System.Linq; // Make LINQ extension methods available
...
foreach (SubA a in Parent.GetList().OfType<SubA>())
{
...
}
Note that a will never be null in the above - I'm assuming that's okay.
Use OfType<T> documented here.
foreach(SubA a in Parent.GetList().OfType<SubA>())
To get a particular instance you can use the Single or SingleOrDefault extension methods on the array. Single will throw an exception if the collection does not contain a matching element; SingleOrDefault will return null.
If you are looking for one object of a certain type
var result = parents.Single(p => p is SubA);
If the objects have a key
var result = parents.Single(p => p is SubA and p.Id == id);
Or you supply whatever criteria allows you to identify the instance.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
LINQ to SQL: Return anonymous type?
Do any one know how to return an anonymous type. I am using Linq where i need to return the following code
private <What's the return type to be provided here> SampleLinq(Int32 Num)
{
var query = (from dept in obj.DeptTable where dept.Id == Num select new { dept.DeptName, dept.DeptId });
return (query)
}
Sorry to say but you cannot return anonymous type out side the scope of method.
This is the alternate way to get anonmous type
// Method that returns anonymous type as object
object ReturnAnonymous()
{
return new { City="Prague", Name="Tomas" };
}
// Application entry-point
void Main()
{
// Get instance of anonymous type with 'City' and 'Name' properties
object o = ReturnAnonymous();
// This call to 'Cast' method converts first parameter (object) to the
// same type as the type of second parameter - which is in this case
// anonymous type with 'City' and 'Name' properties
var typed = Cast(o, new { City="", Name="" });
Console.WriteLine("Name={0}, City={1}", typed.Name, typed.City);
}
// Cast method - thanks to type inference when calling methods it
// is possible to cast object to type without knowing the type name
T Cast<T>(object obj, T type)
{
return (T)obj;
}
you can use it only for types in one assembly (two anonymous types from two different assemblies will be internally compiled to two different types that can't be converted using this trick).
Return Dynamic type:
public static dynamic getCustomer()
{
.....
var x = from c in customers
select new {Fname = c.FirstName};
return x;
}
static void Main(string[] args)
{
dynamic x = getCustomer();
Console.WriteLine(Enumerable.First(x).Fname);
Console.ReadKey();
}
you can't do that. that is why it is called anonymous. It doesn't have a name. But you always can cast it to object
Well, you can't actually do that, but here's a hack on this.
private object SampleLinq(Int32 Num)
{
return (from dept in obj.DeptTable where dept.Id == Num select new { dept.DeptName, dept.DeptId });
}
You can't return an Anonymous Type from a method.
You can create a simple Class to wrap the Anonymous Type, but you still need a Class (or cast to object).
Keep in mind, though, that if you cast to object there's no way to cast back. You'll need reflection to read any data.
The answers you see from the hack is a lot of work just to get an anonymous type through a method boundary. You shouldn't be doing this. If you need to pass something back from a method, you should be passing concrete types.
It depends what you looking to do with the return vale.
If your going to bind it in the UI
you can just rerun
IEnumerable or IQueryable.
If your going to use reflection on the return value just return type object
If your using c# 4.0 you can return a
dynamic type
If your using EF or Linq to SQL to further join a query comprised of your anonymous type you
can make a concrete class instead and
use the concrete placeholder
technique. For more details on this
technique I can give some assistance.
As others have mentioned though, you should really question whether returning an anonymous type form a method is the best way to solve the problem at hand. In general there is usually a better more pattern based approach that may require a bit more coding up front but may resulting in a more elegant design. This being said, I do believe there are legitimate cases such as with data binding where returning anonymous type instances can be perfectly acceptable.
UPDATE:
Just an interested tidbit I wanted to share in case those reading are not aware. Anonymous types are unique per their property names and types so lets say you have method A and method B in in both you create an anonymous type that has a single string typed property called Name by doing something like be code below.
public object A()
{
return new { Name = "Cid" }
}
public object B()
{
return new { Name = "Galuf" }
}
public void Test()
{
System.Diagnostics.Trace.Assert(A().GetType() == B().GetType());
}
Now even though this type is defined in two separate places the compiler only creates only creates a single shared type because they both have the same set of properties as defined by the property types and property names. In this respect the properties can be thought of as sort of a signature for the anonymous type. Using this knowledge there are different techniques that can be used for introspection into anonymous type instances that have been cast to object or deferred using the dynamic keyword. There are also nifty ways to work with anonymous types by using generic methods just as Linq does with methods in the static Enumerable and Queryable classes. This way you can do things like create a new instance of any given anonymous type and without using reflection. The trick is though that you have to use an instance of the anonymous type to pass to methods in order to have the type be inferred by the generic method. If anybody is interested in these topics further as they apply to the original posters question, leave a comment and I can try to clarify some of these techniques.