I am using Nucleon Database Master, which so far has been great for managing my mongodb servers. However, there are a few examples where they show the LINQ Query editor in use with your own data types and classes, but I can't find any documentation anywhere on how to do it.
There are hints in the comments in the c# query it generates:
//Linq to MongoDB Help:http://www.mongodb.org/display/DOCS/CSharp+Driver+LINQ+Tutorial
//The following sample shows a LINQ to MongoDB query. Use #FileInclude command to add your entity class for LINQ Query.
//var collection = this.db.GetCollection<Employee>("Employees");
//var result = from emp in collection.AsQueryable<Employee>()
//where emp.FirstName == "Andrew"
//select emp;
//Output(result);
Everything in the editor works great, apart from I have no idea how to "Use #FileInclude command to add your entity class LINQ Query".
I'm sure it's possible as they have screenshots demonstrating it on their website (I have emailed them, but haven't got a response).
http://www.nucleonsoftware.com/images/dm/LinqToEF_Select1.png
So, anyone either know how to do this, or otherwise have an idea what the #FileInclude thing might be about?
Have had a response back from Nucleon Software, and thought I'd share it here for anyone else with the same question:
You need to add a comment at the top of the query editor, e.g.:
//#FileInclude C:\myFile.cs
using System;
using System;
using System.Collections.Generic;
....
However, they apparently will soon be adding a feature to add you custom DLL's to the LINQ query.
Related
In ADO.Net I created a DAL file that took parameters from the user and if they were not null, the query got extended based on if statements. Now I want to do the same in Entity Framework.
I have searched a number of sites including Stack Overflow but failed to get my satisfactory answer.
for Reference, the following link also could not help me
Select Query with Where condition depending on list values in asp.net
the required scenario is
cmd.text = "SELECT FROM tbl_name WHERE id>0 "
if(param_value != null)
{
cmd.text += " AND (param_name = '#param_value')";
if(!cmd.contains("param_name"))
cmd.parameters.addwithvalue("param_name", #param_value);
cmd.parameters["param_name"] = #param_value;
}
// proceed further with cmd.text
please ignore the syntax right now, I just wanted to convey my concept of what I want to do.
I want to apply the same concept for Entity Framework
Well two days back I found a scenerio in wheich the query (text) was built in an aspx.cs file and it was passed as it is to a custom built function in DAL which passed the text to cmd.text and processed the rest of retrieval in an ADO.net style.
This method is potentially dangerious as anyone with a bit knowlege can break this security down to grounds.
I want to create a query that has parameters as well as its vales like I have shown in above code block.
Using LINQ-to-SQL:
var param_value = 0;
db.tbl_name.Where(x => x.id > 0).Where(x => x.some_property == param_value).ToString();
If you look at the generated SQL, you'll see that's its parameterized (it picks the param_names, though).
I added the ToString() at the end, just so you could see the resulting SQL; based on OP, I'd say to leave this off, and keep modifying the query further directly in LINQ, rather than converting to SQL as a string and concatenating.
I just found out working with Entity framework is a totally different world that classic approach. In here, we work with models/objects and their relationships with each other and we access them based on that relationship. So to answer the question we need to get that model first like
Movie movie = db.Movies.Find(id);
and than from that, we get a model object which does have different properties in it like title, IMDb, rating etc.
We get them repeatedly using where clause as below:
db.Where(movies=>movies.IMDb==10).Where(movies=>movies.title=="The Game Plan")
this all is equal to the following in classic approach
AND (IMDb = 10) AND (title = 'The Game Plan')
following that, one can extend his query as much as he likes.
Again ignore the syntax here because I am here t convey the idea only.
For reference, the following links might be helpful keeping in mind the context i have explained.
Multiple where conditions in EF - StackOverflow
I am using Lightswitch to build my application and I have the following problem.
In my database, I have three tables:
Article
Provider
ArticleProvider
Article and Provider have a many-to-many relation, therefore junction table ArticleProvider is needed.
Now, I want a screen in my application where the user can choose a provider and sees all articles which have a relation to this provider.
Using SQL, I would to it like this (123 is the Provider_Id I want to select).
SELECT *
FROM Article a
WHERE a.Id IN
(SELECT ap.Article_Id FROM ArticleProvider ap WHERE ap.Provider_Id=123)
In my Lightswitch application, I created a Query by clicking on the "Articles" Table in my Datasource and choosed "Add Query". I added a parameter ProviderId and switched to the source code editor to create my custom query:
partial void ArticleByProvider_PreprocessQuery(int? ProviderId,
ref IQueryable<Article> query)
{
...
}
Next I started to create my Linq Query. I think I need an IQueryable<ArticleProvider> Query to filter by them, so I tried:
(from art in query select art.ProviderQuery).AsQueryable<ArticleProvider>()
But, when trying this, I get a compile time error saying that this type can not be converted. So I tried this and it compiles fine:
(from art in query select art.ProviderQuery)
.AsQueryable<IDataServiceQueryable<ArticleProvider>>()
However, when using the returned IQueryable apList in my next query:
from ap in apList where ap.Provider.Id == 123 select ap.Article.Id
It seems that the fields Provider and Article can not be found. Also Visual Studio's code completion does not suggest these fields, only lots of methods and fields which are not in my database.
How can I solve this problem?
I played around with casts and other method calls like ToList(), but I get always stuck at this point. I am new to Linq and C#. Thank you in advance for any help.
EDIT:
I checked the return type of the first query by using:
var temp = (from art in query select art.ProviderQuery).AsQueryable()
The returned type is System.Linq.IQueryable<Microsoft.LightSwitch.IDataServiceQueryable<LightSwitchApplication.ArticleProvider>>
Your problem is that you are in the PreprocessQuery
This is for filtering data further, not adding extra.
If you look around a little this is mentioned a lot.
Give this query a try and see if this works:
partial void ArticleByProvider_PreprocessQuery(int? ProviderId,
ref IQueryable<Article> query)
{
query.Where(art => art.ArticleProviders
.Any(artProv => artProv.Provider.Id == ProviderId));
}
The idea is to get all Articles that at least matches the Provider Id.
Note: Haven't tested this code myself. But the idea should be there.
Quick syntax question: I can return TFS items just fine using several other clauses, but I need to search by specific keyword. Query below:
WorkItemCollection results = wis.Query("SELECT [System.Id] FROM WorkItems WHERE [System.WorkItemType] = 'Dev Bug' AND [System.Keywords] = 'constellation'");
System.Keywords is the problem, this part of the clause is not correct. But I cannot find the right syntax anywhere. Help please!!
In future, if you run into a situation where you aren't sure about the name of the work item field. You can connect to the TFS database, open the team project collection database and look at the fields table.
Lets say for example [Tfs_DefaultCollection].[dbo].[Fields]. This will show you the field name, reference name, field Id, etc.
I want to simply search a database for a certain string, how can i accomplish this using linq and EF (if using these tools for it are not practical I am open to any suggestions). I just want to take a string and search my usernames, the search should be able to handle things only parts of the username (using some sort of 'contains' function)
The basics of what you are asking is..
var found = MyContext.Users.Where(user => user.UserName.Contains(searchString));
You would need to substitute actual entity names/values for the example code posted.
I am new at LINQ and really need a help with some coding.
At the moment, I have a string and a var variables.
string temp = "from product in myEntities.Products where product.Name.Contains(_Name) select product";
var _Products = temp;
LvProducts.DataSource = _Products;
LvProducts.DataBind();
Basically, what I want to do is to be able to create a custom/complicated LINQ query by assigning it into a string beforehand. After done with composing, I assign the string into the var variable. However, this is obviously will not work. Therefore, can anyone assist me on this?
You have a few options:
Use the the Dynamic Linq
libraries to construct you queries on
the fly. The best place to get
started is by reading ScottGu's blog
entry. However, I don't think
these libraries support the contains
method in your example. Here is
a blog post explaining how to add
this support.
Directly execute SQL statements. Check out the MSDN docs for Linq to Sql or Linq to Entities.
var _Products = myEntities.ExecuteStoreQuery<Product>
(#"SELECT * FROM Products WHERE [Name] In ('Item1', 'Item2')");
Use Linq's composable behaviour. This might not be the most elegant solution but it works really well if you do not have too many options. You can just construct your query in multiple parts.
var _Products = from product in myEntities.Products
select product
_Products = from product in _Products
where product.Name.Contains(_Name)
select product
if FilterByPrice {
_Products = from product in _Products
where product.Price > 100
select product
}
You can do this by compiling this Linq within some c# using the CodeDomProvider - Adding scripting functionality to .NET applications - but this is quite heavyweight as a solution. If you want to see more about how to do this, then take a look at LinqPad - http://www.linqpad.net - the author invites you to use the decompiler to see how it works!
If the requirement is just down to simple where clauses than an alternative might be to use Dynamic Linq - see Scott Gu's posts and the sample code from Microsoft - http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx
Maybe this can help you
http://nlinq.codeplex.com/
BR.
Much of the reason you use LINQ in the first place is to get compiler-verified queries, that wil ldetect errors at compile time. This will defeat that purpose since the string will be parsed at runtime.
For your needs you have two options:
1) Making a eSQL query and running it on the ObjectContext. Using this, you can still use your entities like myEntities.Products, and return a list of products.
2) Using a normal SQL query, and use the ObjectContext to call that directly towards the underlying database.
My guess is that you will have to use dynamic code execution. For further details, have a look at Ricks post on west-wind.
you're thinking of it like a Dynamic SQL where you create the statement as string and parse it as a SQL statement.
Since you're already in the code, why not make the statements right in there. It would be a lot easier if you use Lambda instead of the traditional linq. my 2 cents.