Cannot map raw SQL query to DataRow - linq

I am trying to get IEnumerable from linq query below. What am I doing wrong?
IEnumerable<DataRow> results =
context.Database.SqlQuery<DataRow>("SELECT * FROM Customer").AsEnumerable();

DataRow class does not have default (parameterless) constructor, so you can't use it as query parameter type. There is no generic constraints on type parameter, and nothing mentioned on MSDN(!), but column map factory will throw exception if parameter type does not have default constructor:
The result type 'System.Data.DataRow' may not be abstract and must
include a default constructor.
Here is a code which throws this exception:
internal static CollectionColumnMap CreateColumnMapFromReaderAndClrType(
DbDataReader reader, Type type, MetadataWorkspace workspace)
{
BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
ConstructorInfo constructor = type.GetConstructor(flags, (Binder) null, Type.EmptyTypes, (ParameterModifier[]) null);
if (type.IsAbstract || (ConstructorInfo) null == constructor && !type.IsValueType)
throw EntityUtil.InvalidOperation(InvalidTypeForStoreQuery((object) type));
// ...
}
BTW Mapping to DataRow makes no sense, even if it would have default public constructor. Because it is not simple primitive type and it does not have properties which match the names of columns returned from the query (yes, mapping uses properties only).
Correct usage of Linq will be
IEnumerable<Customer> results = context.Customers;
That will generate SELECT * FROM Customer query, and map query results to customer entities. If you really want to use raw SQL:
IEnumerable<Customer> results =
context.Database.SqlQuery<Customer>("SELECT * FROM Customers");

I think we were trying to solve the same problem (Google led me here, anyway). I am executing a raw SQL command through SqlQuery<TElement>(string sql, params object[] parameters and wanted to assert individual properties of the results returned from the query in a unit test.
I called the method:
var result = (db.SqlQuery<Customer>("select * from customers").First();
and verified the data it returned:
Assert.AreEqual("John", result.FirstName);
I defined a private class Customer inside my test class (unfortunately, I'm not using Entity Framework):
private class Customer
{
public string FirstName { get; set; }
}
The properties of Customer must match the column names returned in the SQL query, and they must be properties (not just variables of the Customer class. You don't have to create properties for all of the columns returned from the query.

Related

spring-data-mongodb Query.fields().slice() on #DBRef field throws MappingException

I have a problem with sliced access to some #DBRef field in my model. I use spring-data-mongodb-1.8.0.M1.jar
The model is like:
class Model {
....
#DBRef
List<OtherModel> members;
...
}
and I need sliced access to the members variable.
I use this query:
ObjectId objectId = new ObjectId("55c36f44f359d8a455a21f68");
Query query = new Query(Criteria.where("_id").is(objectId));
query.fields().slice("members", pageable.getOffset(), pageable.getPageSize());
List<Model> models = mongoTemplate.findOne(query, Model.class);
But I get this exception:
org.springframework.data.mapping.model.MappingException: No id property found on class class [Ljava.lang.Integer;
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.createDBRef(MappingMongoConverter.java:842)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.toDBRef(MappingMongoConverter.java:329)
at org.springframework.data.mongodb.core.convert.QueryMapper.createDbRefFor(QueryMapper.java:460)
at org.springframework.data.mongodb.core.convert.QueryMapper.convertAssociation(QueryMapper.java:417)
at org.springframework.data.mongodb.core.convert.QueryMapper.convertAssociation(QueryMapper.java:378)
at org.springframework.data.mongodb.core.convert.QueryMapper.getMappedKeyword(QueryMapper.java:257)
at org.springframework.data.mongodb.core.convert.QueryMapper.getMappedObjectForField(QueryMapper.java:200)
at org.springframework.data.mongodb.core.convert.QueryMapper.getMappedObject(QueryMapper.java:123)
at org.springframework.data.mongodb.core.MongoTemplate.doFindOne(MongoTemplate.java:1647)
at org.springframework.data.mongodb.core.MongoTemplate.findOne(MongoTemplate.java:563)
at org.springframework.data.mongodb.core.MongoTemplate.findOne(MongoTemplate.java:558)
where a field
boolean needsAssociationConversion = property.isAssociation() && !keyword.isExists();
is set. It checks against isExists, but not against something like isSliced (which does not yet exist) and therefore is evaluated to true and, as a cause, tries to convert the non-existing association which is, in this case, just the slice-directive (an integer array). When I set the variable needsAssociationConversion to false while debugging, as if a kind of keyword.isSlice() check was done, everything works fine.
Is this a bug?
Executable project is here
https://github.com/zhsyourai/sliceDemo

what is a projection in LINQ, as in .Select()

I typically do mobile app development, which doesn't always have .Select. However, I've seen this used a bit, but I don't really know what it does or how it's doing whatever it does. It is anything like
from a in list select a // a.Property // new Thing { a.Property}
I'm asking because when I've seen code using .Select(), I was a bit confused by what it was doing.
.Select() is from method syntax for LINQ, select in your code from a in list select a is for query syntax. Both are same, query syntax compiles into method syntax.
You may see: Query Syntax and Method Syntax in LINQ (C#)
Projection:
Projection Operations - MSDN
Projection refers to the operation of transforming an object into a
new form that often consists only of those properties that will be
subsequently used. By using projection, you can construct a new type
that is built from each object. You can project a property and perform
a mathematical function on it. You can also project the original
object without changing it.
You may also see:
LINQ Projection
The process of transforming the results of a query is called
projection. You can project the results of a query after any filters
have been applied to change the type of the collection that is
returned.
Example from MSDN
List<string> words = new List<string>() { "an", "apple", "a", "day" };
var query = from word in words
select word.Substring(0, 1);
In the above example only first character from each string instance is selected / projected.
You can also select some fields from your collection and create an anonymous type or an instance of existing class, that process is called projection.
from a in list select new { ID = a.Id}
In the above code field Id is projected into an anonymous type ignoring other fields. Consider that your list has an object of type MyClass defined like:
class MyClass
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
Now you can project the Id and Name to an anonymous type like:
Query Syntax:
var result = from a in list
select new
{
ID = a.Id,
Name = a.Name,
};
Method Syntax
var result = list.Select(r => new { ID = r.Id, Name = r.Name });
You can also project result to a new class. Consider you have a class like:
class TemporaryHolderClass
{
public int Id { get; set; }
public string Name { get; set; }
}
Then you can do:
Query Syntax:
var result = from a in list
select new TemporaryHolderClass
{
Id = a.Id,
Name = a.Name,
};
Method Syntax:
var result = list.Select(r => new TemporaryHolderClass
{
Id = r.Id,
Name = r.Name
});
You can also project to the same class, provided you are not trying to project to classes generated/created for LINQ to SQL or Entity Framework.
My summary is it takes results (or a subset of results) and allows you to quickly restructure it for use in the local context.
The select clause produces the results of the query and specifies the
"shape" or type of each returned element. For example, you can specify
whether your results will consist of complete Customer objects, just
one member, a subset of members, or some completely different result
type based on a computation or new object creation.
Source: http://msdn.microsoft.com/en-us/library/bb397927.aspx
There are a lot of possible uses for this but one is taking a complex object which of many other contains a property that is a string -- say Name -- and allows you to return an enumeration with just the entries of Name. I believe you can also do the opposite -- use that property ( for example) and create / return new type of object while passing in a property or properties.
It means "mapping". Map each element of a sequence to a transformed sequence. I hadn't comprehended its meaning before I looked at the image.
Where does the meaning of the word come from?
Simply, math! https://mathworld.wolfram.com/Projection.html

Dynamically pass Type to Method<T>

I've a method , that retrieves to me some data according to some type I passed in parameter, like this :
protected void FillList<TEntity>()
{
doWorkForTEntity();
}
I Need to dynamically call this method :
Type[] entities = System.Reflection.Assembly.GetAssembly(typeof(User)).GetTypes();
Type currentEntity = (from entity in entities
where entity.Name.Equals(this.targetEntity)
select entity).FirstOrDefault();
FillList<currentEntity>();
I got this error :
The type or namespace name 'currentEntity' could not be found (are you missing a using directive or an assembly reference?)
I've tried an intermediate object type, no success
Any Idea please ?
Since there is no information about entity type in compile time, you need to construct and call appropriate method by reflection:
Type[] entities = System.Reflection.Assembly.GetAssembly(typeof(User)).GetTypes();
Type currentEntity = (from entity in entities
where entity.Name.Equals(this.targetEntity)
select entity).FirstOrDefault();
var method = this.GetType().GetMethod("FillList", BindingFlags.Instance | BindingFlags.NonPublic)
.MakeGenericMethod(currentEntity);
method.Invoke(this, new object[0]);
You need to do that with reflection as well, so it won't fail in compile time (compiler checks):
Generic class:
Type[] entities = System.Reflection.Assembly.GetAssembly(typeof(User)).GetTypes();
Type currentEntity = (from entity in entities
where entity.Name.Equals(this.targetEntity)
select entity).FirstOrDefault();
Type fillListType= typeof(FillList<>);
Type constructedGenericClass = fillListType.MakeGenericType(currentEntity);
object myList = Activator.CreateInstance(constructedGenericClass );
Generic Method:
Type[] entities = System.Reflection.Assembly.GetAssembly(typeof(User)).GetTypes();
Type currentEntity = (from entity in entities
where entity.Name.Equals(this.targetEntity)
select entity).FirstOrDefault();
MethodInfo methodinfo = this.GetType().GetMethod("FillList");
MethodInfo genericMethod = method.MakeGenericMethod(currentEntity);
genericMethod.Invoke(this, null);
Type parameters must be specified at compile time and can´t be assigned at runtime like in your example. You get the error message because there´s no Type called currentEntiry since it´s just a variable.
Change your method to take an instance of the Type TEntity:
protected void FillList<TEntity>(TEntity instance)
{
doWorkForTEntity();
}
Create a dynamic instance from the Type name and then call the modified method:
dynamic instance = Activator.CreateInstance(this.targetEntity);
FillList(instance);
The dynamic type is basically doing what the other answers have shown you - but IMHO this code is neater and clearer in its intent.

Cast between Oracle Table field and Entity framework fails

Within a WCF web service I make a query on a ORACLE 11g database and I use entity framework as model. The target field is of type Numeric, while in the entity framework is Int64.
When I try to update the field I get the following exception: The specified cast from a materialized 'System.Decimal' type to the 'System.Int64' type is not valid.
The method generating the error is below, in particular for the line within the else statement: result = _context.ExecuteStoreQuery(query).FirstOrDefault();
public string GetDatabaseTimestamp(Type timestampFieldType, string query)
{
object result;
if (timestampFieldType == typeof(string))
{
result = _context.ExecuteStoreQuery<string>(query).FirstOrDefault();
}
else
{
result = _context.ExecuteStoreQuery<long>(query).FirstOrDefault();
}
return result.ToString();
}
Would it be possible to define at the EF level a converter or something similar? The option of changing the Database is not feasible, therefore I have to edit code.
In The EF I already changed the type into decimal. Problem is that the query was executed directly on the Oracle database and this was generating the exception.
I solved the issue by using attributes for the target entity and changed the method into:
public string GetDatabaseTimestamp(Type timestampFieldType, string query)
{
object result;
if (timestampFieldType == typeof(string))
{
result = _context.ExecuteStoreQuery<string>(query).FirstOrDefault();
}
else if (timestampFieldType == typeof(decimal))
{
result = _context.ExecuteStoreQuery<decimal>(query).FirstOrDefault();
}
else
{
result = _context.ExecuteStoreQuery<long>(query).FirstOrDefault();
}
return result.ToString();
}
In this way the passed timestampFieldType is of type decimal and the proper cast is selected. This issue is due to different data types used for similar fields (as example Update fields) in the Oracle DB (legacy database).

Why am I getting a MissingMethodException with querying the TableServiceContext?

I am trying to query a Azure Table Storage. For that I use the following two methods:
TableServiceContext:
public IQueryable<T> QueryEntities<T>(string tableName) where T : TableServiceEntity
{
this.ResolveType = (unused) => typeof(T);
return this.CreateQuery<T>(tableName);
}
Code that uses the method above:
CloudStorageAccount account = AzureConnector.GetCloudStorageAccount(AppSettingsVariables.TableStorageConnection);
AzureTableStorageContext context = new AzureTableStorageContext(account.TableEndpoint.ToString(), account.Credentials);
// Checks if the setting already exists in the Azure table storage. Returns null if not exists.
var existsQuery = from e in context.QueryEntities<ServiceSettingEntity>(TableName)
where e.ServiceName.Equals(this.ServiceName) && e.SettingName.Equals(settingName)
select e;
ServiceSettingEntity existingSettginEntity = existsQuery.FirstOrDefault();
The LINQ query above generates the following request url:
http://127.0.0.1:10002/devstoreaccount1/PublicSpaceNotificationSettingsTable()?$filter=(ServiceName eq 'PublicSpaceNotification') and (SettingName eq 'expectiss')
The code in the class generates the following MissingMethodException:
I have looked at the supported LINQ Queries for the Table API;
Looked at several working stackoverflow solutions;
Tried IgnoreResourceNotFoundException on the TableServiceContext (usercomments of QueryOperators);
Tried to convert the linq query with ToList() before calling first or default (usercomments of QueryOperators).
but I can't get this to work.
Make sure you have parameterless constructor for the class "ServerSettingEntity". The ‘DTO’ that inherits TableServiceEntity needs a constructor with no parameters.

Resources