i would like to make a linq to sql provider that allow to me to query onto a table that is nor mapped in the datamodel nor known.
I only know a table's alias that i use to query another known table for translation (from the alias to the real table name), after that i will using standard linq to query the real table, read data, and put each results into a dynamic's object.
To achieve that i suppose i need to define a custom linq provider that will manipulate the expression tree, and then call standard linq to sql; but at moment i don't know how do it.
So my aim is that i would write code like this :
List<dynamic> rows = form book in context.Book
where book.Author = "Author"
select book;
Thank in advance for any suggestion.
You can use Reflection:
PropertyInfo table = typeof(ContextType).GetProperty(TableName);
from book in table.GetValue(Context)
...
Related
To be clear, I am not referring to performing a .Cast<T> on the results of an EF call.
I'm trying to implement a partial search on a number field.
When creating a SQL script, it is easy to convert a column to another data type:
SELECT Id
FROM Employees
WHERE CAST(Id AS VARCHAR) LIKE '%95%';
Is there any sort of equivalent in a LINQ query?
I can't modify the datatypes on the entity that I'm querying, and Id was just for demonstration purposes.
I do not know why ToString doesn't work, but this is what works for me. Without needing SqlFunctions:
context.Employees.Where(emp => emp.Id.ToString().Contains("95")).ToList();
You can use SqlFunctions.StringConvert:
var q = db.Employees
.Where(emp => SqlFunctions.StringConvert((decimal) emp.Id).Contains("95"));
If you can't find a SqlFunctions solution, there's always ExecuteQuery
var ids = db.ExecuteQuery<int>("SELECT Id FROM Employees WHERE CAST(Id AS VARCHAR) LIKE '%{0}%'", "95")
(This may not be exactly correct for the parameter.)
I'm working on an ASP.Net application which uses a SQL-Server DB and database entities.
Further i got three database entities which are dependend on each other.
This is the dependency hierarchy:
Instance (Key: InstanceID)
CustomField (Key: CustomFieldID, InstanceID)
CustomFieldData (Keys: CustomFieldDataID, CustomFieldID)
CustomFieldData_Person (Keys: CustomFieldData_PersonID, CustomFieldDataID)
I can find out the entries from the entity CustomField by this with the InstanceID:
var customFieldEntries = DB_Instance_Singleton.getInstance.CustomField.Where(x => x.InstanceID == instanceId);
Now i want to find out all entries from CustomFieldData_Person which belong to the hierarchy with the InstanceID as key.
In SQL i would write something like this:
SELECT * FROM CustomFieldData_Person WHERE CustomFieldDataID in (
SELECT * FROM CustomFieldData WHERE CustomFieldID in (
SELECT * FROM CustomField WHERE InstanceID = instanceId))
Unfortunately i'm absolutely new to LINQ.
So my question is, how can i write such a nested query in LINQ (aacording to the first code example above)?
Thanks in advance!
Firstly if you create your ER model correctly you will have most of that logic already set up for you
Person would have a property Person.CustomData which would have Properties for Field and Value so you can just navigate the object structure
however if you dont have that then you can just convert the in statements to Contains
CustomFieldData_Person.Where(cfdp=>CustomFieldData.Where(nested query for CustomFieldData).Contains(cfdp.CustomFieldDataID )
I think this link could be a good starting point for your question. Anyway take a look at Pranav's comment, it points to a helpful question
Sounds trivial but I cannot find an elegant answer to this: how do I read all rows of a specific column into a list of strings for instance using LINQ on Entity Framework context?
You could try something as simple as the following:
var rows = dbContext.TableName.Select(x=>x.ColumName);
where dbContext is the class you use to "talk" with your database, TableName is the name of the table, whose column values you want to read and ColumnName is the name of the column.
Furthermore, if you place a ToList after the Select, you will create list of objects whose type would be the type of the values in column called ColumnName.
Christos answer will just give you an IQueryable. If you want an actual List you need to do something with the IQueryable:
var rows = dbContext.TableName.Select(x=>x.ColumName).ToList();
though I might go for the LINQ syntax:
var rows = (from c in dbContext.TableName
select c.ColumnName).ToList();
The two forms are equivalent.
I'm using LINQ to SQL in C# in my application. I need to be able to select a column of a row, depending upon a variable. This is easy for the row as it's a simple where clause, but I'm at a loss with only selecting a specific column. Here is my code so far:
var permissions = (from s in dc.Permissions where s.dashboardname == permission select s.[variablehere]).Single();
Is this easy to accomplish?
Is it possible to change your database structure so that your columns becomes rows? (Pivot your table?)
Eg.
Permissions Table
-----------------
Id
Dashboardname
Page1
Page2
Page3
...
and turn it into
Permissions Table
-----------------
Id
Dashboardname
Pagename
Then you could use the where clause to select the row you want?
I'm not sure that I understand your question completely, so this might be a bit off. But could your problem perhaps be solved by using the LINQ Dynamic Query Library?
You can use the DynamicQuery library
against any LINQ data provider
(including LINQ to SQL, LINQ to
Objects, LINQ to XML, LINQ to
Entities, LINQ to SharePoint, LINQ to
TerraServer, etc). Instead of using
language operators or type-safe lambda
extension methods to construct your
LINQ queries, the dynamic query
library provides you with string based
extension methods that you can pass
any string expression into.
See the above link for samples and downloads.
I don't think this is either possible or a good practice. Note that if the variable name is provided by user he or she can easily take all the data they want. Maybe you should try using enumeration and switch() clause?
Say the class that holds the permissions is named Permission, you can define an extension method:
public static class PermissionExtensions
{
public static object SelectProperty(this Permission obj, string variable)
{
return obj.GetType().GetProperty(variable).GetValue(obj, null);
}
}
You can use this in your query like this:
(from s in dc.Permissions where s.dashboardname == permission select s)
.Single().SelectProperty(variable);
This doesn't select the property in the query but instead gets it from the instance.
Another answer that came in my mind is to create table with key-value pairs i.e.
dashboard
key
value
where primary key is (dashboard, key).
I'm sure this is straight forward but I'm very new to entity queries and has probably been asked before.
What i need to to search for all business in my database where they have a category that exists in a collection of categories I have built up
IList<businessCategory> busCatList;
busCatList.Add(businessCategory.CreatebusinessCategory(1,"Tourism"));
busCatList.Add(businessCategory.CreatebusinessCategory(2,"Accomidation"));
busCatList.Add(businessCategory.CreatebusinessCategory(3,"Entertainment"));
busCatList.Add(businessCategory.CreatebusinessCategory(4,"Bar"));
busCatList.Add(businessCategory.CreatebusinessCategory(5,"Club"));
var items = Data.DBEntities.business.Where(b.businessCategory.Contains(busCatList) );
I know the syntax of the query is wrong but essentially what i what the query to do it pull out all the business where it has a category matching any of the categories in the busCatLsit
In my database one business can be linked to many categories
In SQL I would do
SELECT name FROM business
join businessCategoryRlnshp on businessCategoryRlnshp.businessID = business.ID
where categoryID in (1,2,3)
just trying to read your mind here ;)
var items = busCatList.Where(businessCategory => b.businessCategory.Contains(businessCategory));
I can't really imagine a nice solution in linq - I mean other than some kind of performing the query several times - one for each business category.
However in SQL Server 2008 there is a new feature - passing a table variable to stored procedure. This can be done from code by passing a DataSet with 1 DataTable as a parameter.
You can of course write an extension method for IEnumerable to convert it to a DataSet similar to ToList() or ToDictionary() methods.
Stored procedure returning entities can be used in EntityFramework 1.0 so this should theoretically make the puzzle click.
PS> There's also a solution using E-SQL and probably query builder methods.