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).
Related
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 ?
I create a simple stored procedure with some joins with the customer table and other related tables, which takes in two parameters. I can execute this SP in SQL and works.
I drag and drop this SP to my DBML file and recompile.
I add the below code in order to call the SP and return it in a List
public IQueryable<Entities.Customer> AllCustomerRanges(int CId, int ItemID)
{
List<Entities.Customer> c = myDataContext.spCustomerRanges(CId, ItemID).ToList();
}
This gives me the error:
Cannot implicitly convert type 'System.Collections.Generic.List< spCustomerRangesResult>' to 'System.Collections.Generic.List< Entities.Customer>'
Now i dont have a class spCustomerRangesResult but after some research I'm puzzled if i have done something wrong or if i need to implement a class with all the properties that the Customer class has (which sounds a little long winded) or if i've just made an error.
Any idea of how i can call a SP which shows the data in a List?
new class spCustomerRangesResult automatically generated based on sp result, you should convert it to Entities.Customer like this:
public IQueryable<Entities.Customer> AllCustomerRanges(int CId, int ItemID)
{
var c = myDataContext.spCustomerRanges(CId, ItemID).ToList();
if (c == null)
return null;
var customers = c.Select(a => new Entities.Customer
{
FirstName=a.spResultFirstName,
LastName = a.spResultLastName
//this just example conversion, change it as needed.
});
return customers;
}
please note, that I return IQueryable even though the approach that you take when using ToList() but yet returning IQuerybale may not be needed. I dont know all details so this only to show how to convert but the whole method may need re-factoring.
I'm using the AWS SDK for .NET, and I'm trying to perform a "scan" operation using the "in" operator.
The ScanCondition takes in three arguments, but I'm not sure what the last argument [the values] should be.
Is it an array of strings? (this returns empty, when it should return results)
Is it a comma-delimited list of strings? (this throws an error saying it could not convert a list of strings into a string)
I've tried a number of different things, and nothing has worked.
public void GetUsers()
{
AmazonDynamoDBClient client = new AmazonDynamoDBClient("key", "secret", Amazon.RegionEndpoint.GetBySystemName("systemEndpoint");
DynamoDBContext context = new DynamoDBContext(client);
var results = context.Scan<User>(new ScanCondition("ID", ScanOperator.In, list /* what goes here? */));
}
The values argument should be of type object[].
In your example, (assuming your list is of type int[] or List), it needs to be cast to type object[] first.
var objectValues = list.Select(x => (object)x).ToArray();
var results = context.Scan<User>(new ScanCondition("ID", ScanOperator.In, objectValues));
It's a known usability issue with the API. If your ID property were of type string, it would work as you'd expect.
As the documentation states the object needed is AttributeValueList.
So you will need to wrap your strings as AttributeValues before passing them to the Scan command
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.
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.