I have a model class that stores information in the datatbase. then I created a list test. This lists get xml data and puts its in a list.
so in my controller,
I have this linq query:
function somefunction()
{
var mov = from m in db.Movies
select m;
List<Movie> items = MyXMLExtract();//this gets xml file from a url, then returns a list<Movie>.
var thistest = mov.ToList().Concat(items);; //I concatenate the two linq
return thistest;
}
in my view I have this:
#model IEnumerable<Models.Movie>
however, everything in this view gives an error:
Unable to create a constant value of type 'Models.Movie'. Only primitive types or enumeration types are supported in this context.
I understand the error, but how to deal with it?
Basically I am returning a list, and I am using Ienumerable, what to do?
my view is just a foreach loop output the fields names.
both movie and items use the same db model from Movies.
this below gives me an error:
Object reference not set to an instance of an object.
if (!String.IsNullOrEmpty(searchString))
{
thistest = thistest.Where(s => s.description.Contains(searchString)
|| s.title.Contains(searchString)
|| s.location.Contains(searchString));
}
LINQ tries to pass List items to DB and concat them on SQL Server side.
change mov.Concat(items); to mov.ToList().Concat(items) to pull data from SQL before concatenation.
Related
I'm building SQL query engine that should take SQL Query as a string in the following format
from (Collection) select (fields) where (conditions)and run it over my Data class (which consists of List fields like List<Person>) and return the result of query
I've already created classes etc. now I just need to run the queries.
Query consists of Source string, ConditionsSet object which have the list of conditions, and Fields string collection which consists of names of fields that we want to display if the record match the conditions.
Let's jump to the code.
public void RunQuery(Data data, Query query)
{
var table = data.GetType().GetField(query.Source).GetValue(data); //Source object
// var output = from entry in table where QueryEngine.IsMatching(entry, query.ConditionsSet) select entry;
// Is something like this is possible? How to approach/do that? Am I forced to not use linq?
// The compiler tells that I cant use Linq because it cant find GetEnumerator in the table object
}
private bool IsMatching(object entry, ConditionsSet set)
{
foreach (Condition c in set.Conditions) // For example we assume the operator is == equality and every condition is separated by AND keyword
if (entry.GetType().GetField(c.Field).GetValue(entry).ToString() != c.Value) //c.Value is string
return false;
return true;
}
How should I approach that? Is LINQ unavailable for me?
I have a stored procedure:
ALTER PROCEDURE [dbo].[GetAllAnnouncements]
AS
BEGIN
SELECT
Description, DisplayStartDate, DisplayEndDate
FROM
Announcements
END
I am trying to call the stored procedure and return it as array, but I get an error:
Cannot implicitly Convert Type MyProject.Models.GetAllAnnouncements_Result[] to string[]
My code:
public string[] getAllAnnouncements()
{
using (PerformanceReviewEntities objContext = new PerformanceReviewEntities())
{
var ann = objContext.GetAllAnnouncements();
string[] DisplayAnn = ann.ToArray();
}
}
I know it has to do something within the edit function import, but I am just not sure what to do. I want to be able to run from home controller, and view it in my .cshtml page.
The function import is returning a collection of objects of type Announcements.
When you call this:
var ann = objContext.GetAllAnnouncements();
ann is a collection of objects, not strings.
Doing this:
string[] DisplayAnn = ann.ToArray();
Wil fail because you are trying to assign an array of objects to an array of strings.
You could do this instead, assuming you are interested in more than one column:
IEnumerable<Announcements> result = ann.ToArray();
And change the signature of your method to return the enumerable:
public IEnumerable<Announcements> getAllAnnouncements()
The call to ToArray() is done to force loading of the results. You don't have to cast it to an array if lazing loading is fine for you. Some people have trouble with that when they try to consume the enumeration after the connection to the database has been closed (e.g. the context is disposed).
I'm trying to build a database using SQLiteAsyncConnection where all of it's queries comes from the server.
database = new SQLiteAsyncConnection(dbPath);
The server's queries are divided into two parts[execution & retrieval]
for the execution queries I'm using this line of code
database.ExecuteAsync(serverResponse);
where serverResponse may be a sql CREATE, INSERT or UPDATE statement.
As for the retrieval queries I'm trying to find a way to retrieve dynamic objects from the database and serialize them to send them to the database. I'm trying to make something like this to retrieve the list of objects in database
var ls = await database.QueryAsync<dynamic>(serverResponse);
but this statement returns a List of objects, and I don't know how to use it.
I tried something like this locally
database.ExecuteAsync("CREATE TABLE Persons(PersonID int);");
database.ExecuteAsync("INSERT INTO Persons(PersonID) VALUES (5);");
var ls = await database.QueryAsync<dynamic>("SELECT * FROM Persons");
int x = ls[0].PersonID;
But it gives me this error 'object' does not contain a definition for 'PersonID'; which says that I need to cast the object to a Person class to be able to use it.(Note that I don't have any class called Person that has a public property PersonID; objects are dynamic and I can't tell what the server's query are).
I tried to serialize ls
string str = JsonConvert.SerializeObject(ls);
but it returns a JSON array with empty object [{}].
How can I serialize the result of any query without the need to cast it.
var ls = await database.QueryAsync<object>("SELECT * FROM Persons");
var json = JsonConvert.SerializeObject(ls);
try this ?
In short i want the following grouping functionality: http://demos.telerik.com/aspnet-mvc/grid/index
However, I cannot seem to figure out how to enable my back end to retrieve this data dynamically.
I have the following line:
query.UnderlyingCriteria.SetProjection(Projections.GroupProperty("PropertyNumber"));
Where query is of type IQueryOver.
However, when I use
var statistics = query.List<T>();
I get
"The value \"000000\" is not of type \"SDS" and cannot be used in this generic collection.\r\nParameter name: value"}
000000 is a default property number, and SDS is the object I'm attempting to group. It is obvious to me that what I've written is attempting to cast strings back as the value.
Interestingly the following returns the exact count of rows in the table.
var rowCount = query.RowCount();
My question then, is how do I actually return SDS in a grouped manner, if the projection cannot do what I want?
There are two issues in general:
once we've used projection, any other property which we want to get must be projected as well.
if there is a projection and we need to get a list of entities, we need result transformer
Having that we can get the list like this:
// the As() is essential for result transformer
query
.UnderlyingCriteria
.SetProjection(Projections.GroupProperty("PropertyNumber")
.As("PropertyNumber"));
// set Transformer
query.TransformUsing(Transformers.AliasToBean<T>());
// the list of T, but only PropertyNumber is filled by NHibernate
var list = query.List<T>();
or this to get more properties filled
query
.UnderlyingCriteria
.SetProjection(
Projections.ProjectionList()
.Add(Projections.GroupProperty("PropertyNumber").As("PropertyNumber"))
.Add(Projections.Count("ID").As("Count"))
....
)
;
// set Transformer to some DTO
query.TransformUsing(Transformers.AliasToBean<U>());
// the list of DTO, with more than PropertyNumber filled
var list = query.List<U>(); // generic U representing DTO
Finally, the QueryOver API has its own way how to declare projections
16.6. Projections
Hi i am trying to get to grips with Dapper.
My situation is i want to pull two values from a query into two separate strings. Im not sure if i am going about this in the correct way, but this is what i am doing:
string sql = #"Select type, name
FROM ZipData
WHERE Zip = #zip";
using (var multi = conn.QueryMultiple(sql, new { zip = zip }))
{
string result = multi.Read<string>().SingleOrDefault();
}
And i am getting Cannot access a disposed object. Object name: 'GridReader'. when trying to read the second string.The thing is it gets the first value correctly and has both the fields in in the reader i am trying to get. Im sure im misusing the api.
What am i doing wrong here? Ive googled but can find a specific example.
You are mis-using QueryMultiple. That is defined for compound SQL statements that return multiple result sets. Something like:
SELECT Foo FROM MyTable;
SELECT Bar FROM MyOtherTable;
On the other hand, you are trying to get two different columns from a single result set, so you should just use the normal Query method:
var result = conn.Query(sql, new { zip = zip }).Single();
var type = result.type;
var name = result.name;
Query returns an enumerable (because generally a query can return multiple rows). It appears that you only want one row, however, so we invoke .Single at the end to just get that row. From there, the return type is dynamic so you can simply refer to the properies implied by the columns in your SELECT statement: type and name.