I'm doing some tests to take a project. I have been working with ASP.NET Core MVC and Entity Framework relatively recently. I have a simple database in SQL Server to prove how it is:
In the test project I have a controller TestController; the code is this:
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using WEBAPPHTTP.Models;
namespace WEBAPPHTTP.Controllers
{
[Route ("api/controller[]")]
public class TestController: Controller
{
[HttpGet("/api/values")]
public IEnumerable<string> Get()
{
using (TareasContext db = new TareasContext())
{
var listar = db.Tareas;
var n = listar.Count();
string[] array = new string[n+1];
int i = 0;
foreach (var otareas in listar)
{
array[i] = otareas.Tarea.ToString();
i = i++;
}
return array;
}
}
}
}
Obviously I'm doing something wrong but the output is this:
in localhost/api/values:
["ahora",null,null,null,null]
It only shows me the last record of the database followed by a few NULL, this test the idea is that all the results are loaded in the array.
I'm sure it's a very early mistake, I hope you can guide me.
I dont know what you want to do after this, but if you just want to list out your items, you should be able to do something like this:
using (TareasContext db = new TareasContext())
{
return db.Tareas.ToList();
}
That will give you the full list with all items in it with all properties, if you want just a part of your properties I would suggest to do a .Select as well.
Remember to do a where as well so you dont always return the full list (if it gets enourmus big)
Peace!
You code is not efficient. This is the much cleaner version that does the same:
using (TareasContext db = new TareasContext())
{
var result = db.Tareas.Select(x => x.Tarea).ToList();
return result;
}
As I see the Tarea column is of varchar or nvarchar type. So, you don't need to cast it to string.
Related
Is is it possible to execute multiple queries using SqlKata at the same time.
Currently I have the following code:
var latestUsersQuery = db.Query("tbl_users").Where("created_at", ">", from);
var activitiesQuery = db.Query("tbl_activities").WhereIn("user_id", latestUsersQuery.Clone());
and I am querying each one alone.
var latestUsers = latestUsersQuery.Get();
var activities = activitiesQuery().Get();
I am wondering if there is a way to execute both queries at the same time.
// for example something like this
var results = db.GetAll(latestUsersQuery, activitiesQuery);
Thanks.
Late to the game on this, but you could extend SqlKata's QueryFactory class similar to how they write the other methods; using extension methods.
using SqlKata;
using SqlKata.Execution;
using System.Collections.Generic;
using System.Linq;
// ...
public static class QueryFactoryExtensions
{
public static IEnumerable<IEnumerable<T>> GetAll<T>(this QueryFactory db, params Query[] queries)
{
return queries.Select(q =>
{
return SqlKata.Execution.QueryFactoryExtensions.Get<T>(db, q);
});
}
public static IEnumerable<IEnumerable<dynamic>> GetAll(this QueryFactory db, params Query[] queries)
{
return GetAll<dynamic>(db, queries);
}
}
The usage would look like:
var query1 = new Query();
var query2 = new Query();
var results = db.GetAll(query1, query2)
From there you could: enumerate over it, cast to an array and access by index, etc.
Bear in mind here, this is not sending one query to the database as mentioned in the comments of the OP. If performance is truly what you're after, then you might look at using the Dapper extension method QueryMultiple instead of Query (which is what SqlKata is calling on the Get() methods). I'm not familiar enough with the underlying magic that Dapper is doing to be able to confidently give you direction. Another possiblity for you could be to add extensions for GetAsync instead of Get. This may be better suited to your needs.
All of that said, at minimum I hope that this provides you with some direction in which to make a decision or potentially benchmark performance.
I am using EF 6 & Visual Studio 13 free community.
I am using database-first approach in my current project.
I created A SQL Server DB project and added it to my project to work with EF
I created tables & some stored procedures. After I added the db to my project it created a class procedure_name_Result and i need to use linq queries in my project but I don't know how to call it in the query, or if it will even recognize it as I can't see it in the uploaded db
EDIT Thanks to you both answers i was able to know how to probably call in a Linq query
var query = from X where Y
select new {
elemnt,
var_inside_query = DB.procedure_name(#params)
};
I use Northwind database as sample project.
using System;
using System.Collections.Generic;
using System.Linq;
namespace EF_SP
{
class Program
{
static void Main(string[] args)
{
using (var context = new NorthwindEntities())
{
var results = context.GetSalesByCategory("Seafood", "1998");
foreach (var result in results)
Console.WriteLine("{0} {1}", result.ProductName, result.TotalPurchase);
}
Console.WriteLine("Press any key. . .");
Console.ReadKey(true);
}
}
}
I'm using the RavenDB streaming API to retrieve all 355,000 DocsToProcess from my database instance using the following code:
_myDocs = new List<DocsToProcess>();
var query = RavenSession.Query<DocsToProcess>();
using (var enumerator = RavenSession.Advanced.Stream(query))
{
while (enumerator.MoveNext())
{
DocsToProcess u = enumerator.Current.Document;
_myDocs.Add(u);
}
}
However, the following exception message is thrown:
StreamQuery does not support querying dynamic indexes. It is designed to be used with large data-sets and is unlikely to return all data-set after 15 sec of indexing, like Query() does.
How I can correctly iterate through all elements of type DocsToProcess in my C# application?
The documentation says explicitly for unbound results:
Important side notes:
the index already exists. Creation of a index won't occur and the query error with an IndexDoesNotExistsException exception.
And that's what your exception is saying. You have to create a static index for streaming results.
Similar to JHo above, the solution that I came up with means that you do not need to make a static index for streaming, because you're relying on the default index and using the StartsWith overload of Stream<T> in the Raven client.
We've found the solution below to work fine for most of our use-cases where we need to get everything from a Raven instance.
public IEnumerable<T> GetAll()
{
var results = new List<T>();
var conventions = _documentStore.Conventions ?? new DocumentConvention();
var defaultIndexStartsWith = conventions.GetTypeTagName(typeof(T));
using(var session = _documentStore.OpenSession())
{
using(var enumerator = session.Advanced.Stream<T>(defaultIndexStartsWith))
{
while(enumerator.MoveNext())
results.Add(enumerator.Current.Document);
}
}
return results;
}
To get by without creating a static index, you can provide some minimal bounding like this:
using (var session = store.OpenSession())
{
IEnumerator<StreamResult<Employee>> stream =
session.Advanced.Stream<Employee>("employees/");
while (stream.MoveNext())
{
// ....
}
}
I am still a beginner at writing C# and SQL and was wondering if someone could help me with this basic question. I have looked all over the internet and am still stuck.
I am trying to write a WCF service to access my database. I only need one method:
public PathDto GetPath(string src, string trg)
{
using (var context = new PathsEntities())
{
var p = (
from a
in context.src
where a.Target = trg
select a).Distance, Path;
}
}
where the parameter src is the table name, and the string trg is the entity's primary key.
Visual studio gives me the error: ...pathsService does not contain a definition for src because it is trying to look up the table "src" and not the string contained in the variable.
How can I use my parameter in the lookup statement?
I am going to assume you are using DbContext EF5.0 stuff
public PathDto GetPath(string tableType, string id)
{
using (var context = new PathsEntities())
{
var type = Type.GetType(tableType);
var p = context.Set(type).Find(id);
return (PathDto)p;
}
}
Seems you DON'T use EF 5.0 and have only got EF 4.0 and are using ObjectContext. Try this...no idea if it works since I don't really use EF 4.0. Alternatively download EF 5.0
public PathDto GetPath(string tableType, string id)
{
using (var context = new PathsEntities())
{
var type = Type.GetType(tableType);
var p = context.GetObjectByKey(new EntityKey(tableType, "id", id));
return (PathDto)p;
}
}
How to write HQL queries using NHibernate. What namespaces will I have to included so that everything works fine. Actually I have 2 tables Ticket and Trip and I wanta count of all the records in Trip that do not have a corresponding entry in Ticket. There is a tid field in ticket that refrences Trip id. Can anybody please explain me from start how will I write a NHibernate HQL query for this?
You don't need any special namespaces to use HQL. Just create a simple NHibernate project and you can start writing HQL right away.
Here is an example from the new NHibernate 3.0 Cookbook and you should also check the Nhibernate in Action book which has a more elaborate examples on HQL.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate.Cfg;
using NHibernate;
namespace ExecutableHQL
{
class Program
{
static void Main(string[] args)
{
log4net.Config.XmlConfigurator.Configure();
var nhConfig = new Configuration().Configure();
var sessionFactory = nhConfig.BuildSessionFactory();
using (var session = sessionFactory.OpenSession())
{
using (var tx = session.BeginTransaction())
{
int count = (int) session.CreateQuery("select count(*) from Trip").UniqueResult();
tx.Commit();
}
}
}
}
}
[HttpGet]
public int GetCount()
{
var myQuery = session.CreateQuery(#"
select COUNT(*) from Table as t where
t.Id = :Id");
myQuery.SetParameter("Id", this.Id);
int count = Convert.ToInt32(myQuery.UniqueResult());
return count;
}