How to access columns from an IQueryable when dynamically constructed? - dynamic

I am using the System.Linq.Data library provided here - http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx
I have the following query which works great and returns an Iqueryable
IQueryable customer =
ctx.Customers.Where(cust => true).Select("new("Name,Address")");
However, how do I access these returned columns? I cannot access them using a lambda expression as follows:
var test = customer.Where(cust=>cust.Name == "Mike").First();
"cust.Name" in the above case cannot be resolved. It does not exist in the list of methods/properties for "cust".
Am i assuming something wrong here. I understand that I am working with an anonymous type. Do I have to create a DTO in this case?

For any IQueryable you have property called ElementType.
You can use it to get the properties as explained below
IQueryable query = from t in db.Cities
selec new
{
Id = t.Id,
CityName = t.Name
};
if(query!=null)
{
Type elementType = query.ElementType;
foreach(PropertyInfo pi in elementType.GetProperties())
{
}
}

Try foreach loop:
var a = _context.SENDERS.Select(x=>new { Address=x.ADDRESS, Company=x.COMPANY });
foreach(var obj in a)
{
Console.WriteLine(obj.Address);
Console.WriteLine(obj.Company);
}

Related

.NET Core - EntityFrameworkCore - Unable to cast object of type 'Query.Internal.EntityQueryable` to type 'DbSet`

I try to implement a search with entity when a search field is provided
but I get a weird casting error I just dont understand
Unable to cast object of type 'Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1[SomeApp.Models.Partner]' to type 'Microsoft.EntityFrameworkCore.DbSet`1[SomeApp.Models.Partner]'.
here is the code of my controller entry point
I tried forcing the cast, but apparently there is something wrong with my code
[HttpPost]
public async Task<ActionResult<PartnersFetch>> GetPartners(PartnersSearch partnersSearch)
{
DbSet<Partner> data = _context.Partners;
if (partnersSearch.SearchById != null)
{
// the following line causes problems :
data = (DbSet <Partner>) data.Where( p => p.Id == partnersSearch.SearchById.GetValueOrDefault());
}
thanks for helping me on this
I forgot to use AsQueryable
var data = _context.Partners.AsQueryable();
if (partnersSearch.SearchById != null)
{
data = data.Where( p => p.Id == partnersSearch.SearchById.GetValueOrDefault());
}
data.Where(...) will return an IQueryable which you can materialize as follows
List<Partner> myResult = data.Where(...).ToList();
The DbSet<Partner> is only the set on which you can query data. Your goal very likely is to get the partners out of it, right?

Getting Custom Column from IQueryable DB First Approach EF

I am working on Database First Approach in Entity Framework where I have to retrieve specific columns from the Entity.
Public IQueryable<Entity.Employees> GetEmployeeName(String FName,String LName)
{
var query = (from s in Employees
where s.firstName = FName && s.lastName = LName
select new {s.firstName, s.middleName});
return query;
}
Here return statement is throwing an error where it seems that its not matching with Employees (entity) columns. Could you please help me in sorting out this issue? Thanks in advance.
You need to use == for comparison, also you need to use dynamic type as return type since you are returning a custom anonymous type. Try this
Public IQueryable<dynamic> GetEmployeeName(String FName,String LName)
{
var query=(from s in Employees
where s.firstName==FName && s.lastName==LName
select new {s.firstName,s.middleName});
return query.AsQueryable();
}
Finally you will use it like below, keep in mind that intelisense won't work on dynamic object.
var query = GetEmployeeName("Jake", "Smith");
List<dynamic> results = query.ToList();
foreach (dynamic result in results)
{
string fristName = result.FirstName;
string lastName = result.MiddleName;
}

SQL Select on MVC4 Controller

I am trying to perform a SELECT on the M1lhao table of Sorteio entity (database).
I don't want to go the traditional "string query" or AddWithParameter() way, i wanted to use the MVC4 EF5 available methods.
The following code passes the entire Table to the View, that i can do a foreach in the View and all works fine. What i am looking for is how can i do a SQL query, so i can pass only the element(s) i want, sorted DESCending (for example), obviously on a List and obeying the Model that the View expects.
Essentially i want a replacement for (i tried variants too, db.Milhao, etc):
var data = db.Database.ExecuteSqlCommand("SELECT * From M1lhao WHERE DrawID = {0}", id);
The problem with Find() is that it only searches primary keys.
The complete code:
public class M1lhaoController : Controller
{
private Sorteio db = new Sorteio();
public ActionResult Index(int id = 1)
{
var data = db.Database.ExecuteSqlCommand("SELECT * From M1lhao WHERE DrawID = {0}", id); // the variable data comes as -1
M1lhao m1lhao = db.M1lhao.Find(id);
if (m1lhao == null)
{
return HttpNotFound();
}
return View(db.M1lhao.ToList());
}
}
Thank you.
You can try as shown below.
var data = db.M1lhao.Where(m=>m.DrawID == id).Select(p=>p);
You can learn more about Method-Based Query Syntax : Projection

RuntimeBinderException on dynamic Linq with Facebook C# SDK

I am using the Facebook C# SDK in a canvas app.
When running this code...
public IEnumerable<string> GetFansIds(string pageId, IEnumerable<string> userIds)
{
if (userIds.Count() == 0)
return new List<string>();
var fb = new FacebookApp();
string query = String.Format("select uid from page_fan where uid IN ( {0} ) and page_id = {1}",
String.Join(",", userIds),
pageId
);
dynamic result = fb.Fql(query);
return result.Select((Func<dynamic, string>)(x => x.uid)).ToList();
}
I get the following Exception:
RuntimeBinderException: Cannot perform runtime binding on a null reference
The code does the following:
It performs a FQL query to get an JsonArray contaning JsonObject each with a uid Property (containing the uids of the users that are not fan of some fanpage.
The Select just converts all the dynamic objects into a List<string>
The FQL part just works correctly as i can see the results in the debugger.
The problem is with the Select that I can't make it work.
How can I fix the dynamic lambda ??? (Please don't just tell me to use a foreach, which is what I am currently doing right now)
The problem is that extension methods cannot be used on dynamic objects. Cast the result of the query to a JsonArray and then you can use linq expressions on the JsonArray.
var result = (JsonArray)fb.Fql(query);
return result.Select((Func<dynamic, string>)(x => x.uid)).ToList();

Can I get the T-SQL query generated from a LinqDataSource?

I´m using the LinqDataSource to populate a grid. But now I need the SQL query that the LinqDataSource generates, to pass around throught methods (no, I can't modify the methods to not need a SQL query).
Is there a way to obtain the generated SQL query from a instantiated and configured LinqDataSource?
Hope this helps.
using the function below will return a SqlQueryText
you can rebuild the query from that object.
to get the sql text you can use use the .Text Property
to get the passed
parameters you can use the .Params property
public static SqlQueryText GetFullQueryInfo(DataContext dataContext, IQueryable query)
{
DbCommand dbCommand = dataContext.GetCommand(query);
var result = new SqlQueryText();
result.Text = dbCommand.CommandText;
int nParams = dbCommand.Parameters.Count;
result.Params = new ParameterText[nParams];
for (int j = 0; j < nParams; j++)
{
var param = new ParameterText();
DbParameter pInfo = dbCommand.Parameters[j];
param.Name = pInfo.ParameterName;
param.SqlType = pInfo.DbType.ToString();
object paramValue = pInfo.Value;
if (paramValue == null)
{
param.Value = null;
}
else
{
param.Value = pInfo.Value.ToString();
}
result.Params[j] = param;
}
return result;
}
here is an example
var results = db.Medias.Where(somepredicatehere);
ClassThatHasThisMethod.GetFullQueryInfo(yourdatacontexthere, results);
EDIT:
Sorry forgot to include the SqlQueryText data structures
public struct SqlQueryText
{
public ParameterText[] Params;
public string Text;
}
public struct ParameterText
{
public string Name;
public string SqlType;
public string Value;
}
You can run SQL Profiler while running your application and that should give it to you.
Take a look at LinqPad for debugging and to understand how it works. But if you want it at run-time, I think you're out of luck.
The Sql will only be generated by the Linq to Sql infrastructure at runtime.
I think there are some tools to see generated Sql in the debugger, but if you don't plan to use linq to generate your Sql dynamicaly, shouldn't you probably look for a simple Sql designer ?
I Found a Linq To Sql Debug visualizer on Scottgu's blog.