i included .NET XPAGED LIST in my project using nuget and is successfully working
the code is
public ActionResult Index(int? page)
{
var query = from p in db.Posts orderby p.ID ascending select p;
Console.WriteLine(query);
var pageNumber = page ?? 1;
ViewData["Posts"] = query.ToPagedList(pageNumber, 10);
return View();
}
the main question is that we are using the query to extract all records. then those are skipped and taken by
.ToPagedList(pageNumber,elementsperpage);
but this creates performance issues.
The query must extract only paged/limited elements like LIMIT(0,5)
do pagedlist limits or i have to create my custom function for paging in asp mvc
Related
The table has to be created dynamically. The table name is dynamic (is sent to API) and columns are static.
Every time api is called, a new table is been created with different name.
Is it possible to do that in Entity Framework? If so - how?
DB is Posstgress.
Thanks
ADO is not the accepted way. I need to do it with Entity Framework.
I tried to write migration that will be activated just when API is called. But it seems that migration can run only when running first.
If you have a bunch of tables with the same columns and you want to switch between them at runtime, you can use SQL Queries.
var blogs = context.Blogs
.FromSql($"SELECT * FROM {QuoteName(tableName)}")
.ToList();
where QuoteName prevents SQL Injection attacks. This one is for SQL Server:
private static string QuoteName(string identifier)
{
var sb = new StringBuilder(identifier.Length + 3, 1024);
sb.Append('[');
foreach (var c in identifier)
{
if (c == ']')
sb.Append(']');
sb.Append(c);
}
sb.Append(']');
return sb.ToString();
}
I have a Web API server (with EF 6.x) and I need to do some post-processing of the result set from OData queries in the controller. On the client-side I use a DevEx grid and their ODataInstantFeedbackSource.
With no post-processing, everything works fine, e.g.:
http://somesite.us/odata/Items/$count
[EnableQuery]
public IHttpActionResult GetItems(ODataQueryOptions<Item> queryOptions)
{
return Ok(Context.Items);
}
It does not work with post-processing (same simple $count query, but without EnableQuery since I am manually applying the query options):
GET http://somesite.us/odata/Items/$count
//[EnableQuery]
public IHttpActionResult GetItems(ODataQueryOptions<Item> queryOptions)
{
queryOptions.Validate(_validationSettings);
var query = queryOptions.ApplyTo(Context.Items, new ODataQuerySettings()) as IQueryable<Item>;
var resultList = new List<Item>();
foreach (var item in query)
{
item.OrdStat = "asf"; // Some post-processing
resultList.Add(item);
}
return Ok(resultList.AsQueryable());
}
This throws an exception:
Microsoft.OData.ODataException
HResult=0x80131509
Message=The value of type 'System.Linq.EnumerableQuery`1[[SomeService.Model.Item, SomeService.Model, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' could not be converted to a raw string.
Source=Microsoft.OData.Core
StackTrace:
at Microsoft.OData.RawValueWriter.WriteRawValue(Object value)
Note: with ODATA v3, the above works just fine. It is only with v4 that I get an exception when not using [EnableQuery].
If I add back the [EnableQuery] attribute, this simple $count query works with ODATA v4, but with more complex queries, the data returned to the client gets messed up (likely due to $skip, etc. being applied both by me and by the EnableQuery attribute).
For example, this query generated by the DevEx grid when you scroll down:
http://somesite.us/odata/Items?$orderby=ItemNo&$skip=300&$top=201
Results in (client-side): Unexpected number of returned keys: 0. Expected: 201
I assume that I need to remove the EnableQuery attribute since I am manually applying the query options, but why am I getting the "could not be converted to a raw string" exception when I do this?
How can I properly implement post-processing in this scenario?
I opened a support request with Microsoft on this, and they eventually determined that it is a bug in ODATA v4 and they created this bug report:
https://github.com/OData/WebApi/issues/1586
The workaround is to check if the query is a count query and, if so, return Ok(query.Count());
if (queryOptions.Context.Path?.Segments.LastOrDefault() is CountSegment)
return Ok(query?.Count());
Here is a more complete sample snippet / POC which works fine with ODATA v4:
private static ODataValidationSettings _validationSettings = new ODataValidationSettings();
[ODataRoute("Customers")]
public IHttpActionResult Get(ODataQueryOptions<CustomerLookup> queryOptions)
{
queryOptions.Validate(_validationSettings);
var query = queryOptions.ApplyTo(Context.CustomerLookup) as IQueryable<CustomerLookup>;
if (queryOptions.Context.Path?.Segments.LastOrDefault() is CountSegment)
return Ok(query?.Count());
var resultList = new List<CustomerLookup>();
foreach (var customer in query)
{
customer.Address = "1234_" + customer.Address;
resultList.Add(customer);
}
return Ok(resultList.AsQueryable());
}
In an ASP.NET MVC Core Web project, without using any third party tools (LINQPad etc.) how can we achieve the above for a LINQ query such as the one shown in an Action Method below.
NOTE:
I'm using EF Core and VS2015
Project is MVC Code First
Action Method:
public async Task<IActionResult> PostBlogs(string returnUrl = null)
{
var qry = from a in _context.Blogs
where a.Url.Contains("Contoso")
return View(await qry.ToListAsync());
}
To see the query result where you have to construct your method as shown below.
public async Task<IActionResult> PostBlogs(string returnUrl = null)
{
var qry = from a in _context.Blogs
where a.Url.Contains("Contoso");
qry = await qry.ToListAsync();//you can see the result here when you expand it
return View(qry);
}
You have to configure like this to see the SQL : Logging
I am using Entity Framework inside an asp.net mvc web application. I have the following query:-
public AccountDefinition GetCustomer2(int id){
var c = entities.AccountDefinitions.Where(s=>s.ORG_ID==id)
.Include(a=>a.SDOrganization)
.Include(a1=>a1.SiteDefinitions);
var c2 = c.Select(a=>a.SDOrganization); //code goes here }
Which is called from the following Action Method:-
public ActionResult Index(int searchTerm)
{ var accountdefinition = repository.GetCustomer2(searchTerm).ToList();
return View(accountdefinition);
}
So when I am creating the c2 var will it query the database or the data will be inside the memory from the first call, when reaching the .Tolist()?.
Second question if I replace the .Include with .Select when creating the Var c, will it have the same effect?
You can see what query is executed in the SQL Server Profiler (if using SQL Server), or you can have a look at some Entity Framework Tracing Provider. http://code.msdn.microsoft.com/EFProviderWrappers-c0b88f32
This will give you lots of information and understanding...
I'm currently planning on switching my "manual query-writing" code to a nice SQL framework, so I can leave the queries or sql things to the framework, instead of writing the queries myself.
Now I'm wondering how I can get a single record from my table in Entity Framework 4?
I've primarily used SQL like SELECT * FROM {0} WHERE Id = {1}. That doesn't work in EF4, as far as I'm concerned.
Is there a way I can select a single ID-Based record from my Context?
Something like:
public Address GetAddress(int addressId)
{
var result = from Context.Addresses where Address.Id = addressId;
Address adr = result as Address;
return Address;
}
Thank you!
var address = Context.Addresses.First(a => a.Id == addressId);
You can use Single or First methods.
The difference between those methods is that Single expects a single row and throws an exception if it doesn't have a single row.
The usage is the same for both of them
(Based on VS 2015) If you create an .edmx (Add --> ADO.NET Entity Data Model).
Go through the steps to created the ".edmx" and use the following to run the stored procedure. emailAddress is the parameter you are passing to the stored procedure g_getLoginStatus. This will pull the first row into LoginStatus and status is a column in the database:
bool verasity = false;
DBNameEntities db = new DBNameEntities(); // Use name of your DBEntities
var LoginStatus = db.g_getLoginStatus(emailAddress).FirstOrDefault();
if ((LoginStatus != null) && (LoginStatus.status == 1))
{
verasity = true;
}