I have several references in DB with same table structure.
I don't want to write several LINQ queries to each db. Is it possible to develop one query with dynamic Table parameter?
My query example:
var query =
from myTranslations in myContext.translations
where myTranslations.code == strLabelCode
select myTranslations;
No, sorry. Simple like that - only via for example reflection, which makes it - ah - hard er than having multiple table objects.
Use datacontext GetTable() method to vary table type as listed here MSDN
Related
I am using LINQ to retrieve data from my EF context as well as from Asp .Net Identity 2.0 - both located in the same MS SQL Server database.
My problem is that LINQ sees them as 2 different cases of data context and is unable to process the query.
"The specified LINQ expression contains references to queries that are associated with different contexts."
What I want to achieve is a simple return of 10 top items (I skip this in the code extract) from EF table, previously sorted by the UserName from ASP .NET Identity table.
I have seen a few cases of this problem on StackOverflow but I was unable to apply any solution in my case.
The preferred solution would be of course not to download all of the table data and do the sorting on the server.
The query in question:
var dbDataSorted = from entry in dbData
join user in this.UserManager.Users
on entry.UserId equals new Guid(user.Id)
orderby user.UserName ascending
select entry;
return dbDataSorted;
I was able to get this to work in my case by using AsEnumerable(). YMMV.
In your case:
var dbDataSorted = from entry in dbData.AsEnumerable()
join user in this.UserManager.Users
on entry.UserId equals new Guid(user.Id)
orderby user.UserName ascending
select entry;
return dbDataSorted;
LINQ and EF are pretty cool. But sometimes, its abstractions don't offer what you need.
Just fall back to base, write the query by hand, put it in a string, run it against yourcontext.YourDbSet with the SqlQuery method, and be done with it.
var query = #"SELECT * FROM dbData as entry
INNER JOIN Users
ON entry.UserId = Users.Id
ORDER BY Users.Username";
yourcontext.dbData.SqlQuery(query);
If the abstractions offered to you don't work with what you need, abusing the abstractions to do something weird is far less clear than using the lower level interface.
You can't use Linq to Entities and Linq to object in one query. It's because when you make query to instance of IQueryable interface, the query will be transformed to SQL, and in SQL you can't use any IEnumerable collection. So you should get data from database (for example dbData.AsEnumerable()).
But if you want do all job on the SQL Server side, the easiest way is to create sql procedure and pass the users table as a parameter. The easiest way to pass users table as xml and than parse it in the procedure on the server side.
If you're using ASP.NET Identity 2 code-first, then your DbContext presumably inherits from IdentityDbContext<>, and so you can access the Users table directly from the context. You don't need to use UserManager to access the users.
Is there's way to execute SQL queries directly on dataset or datatable . Query which need to be executed is much complex and it may be difficult to implement with Linq .
Is there any similar way to query directly from dataset or datatable ?
Is there any tools available to convert complex queries to linq ?
There is a DataTable.Select() method, which returns rows that match certain criteria.
The syntax is a little limited, however. Example:
DataTable.Select("Date > #1/1/2014# AND Name = \"John\"");
Should select any rows where the Date column has a date value that's 1/1/2014 or later, and the Name column is "John". Also handy is using String.Format() with it.
DataTable.Select(String.Format("Date > {0} AND Name = {1}", date, name));
This is severely limited compared to fixing it in the actual query, though.
try to use tools like LinqPad or some thing similiar
Download LinqPad
also one other way is to create your complex queries in database as VIEW and then write a simple select from VIEW!
another approach is, using MethodChain
What is the correct way to chain methods in .Net
I have a setup on SQL Server 2008. I've got three tables. One has a string identifier as a primary key. The second table holds indices into an attribute table. The third simply holds foreign keys into both tables- so that the attributes themselves aren't held in the first table but are instead referred to. Apparently this is common in database normalization, although it is still insane because I know that, since the key is a string, it would take a maximum of 1 attribute per 30 first table room entries to yield a space benefit, let alone the time and complexity problems.
How can I write a LINQ to SQL query to only return values from the first table, such that they hold only specific attributes, as defined in the list in the second table? I attempted to use a Join or GroupJoin, but apparently SQL Server 2008 cannot use a Tuple as the return value.
"I attempted to use a Join or
GroupJoin, but apparently SQL Server
2008 cannot use a Tuple as the return
value".
You can use anonymous types instead of Tuples which are supported by Linq2SQL.
IE:
from x in source group x by new {x.Field1, x.Field2}
I'm not quite clear what you're asking for. Some code might help. Are you looking for something like this?
var q = from i in ctx.Items
select new
{
i.ItemId,
i.ItemTitle,
Attributes = from map in i.AttributeMaps
select map.Attribute
};
I use this page all the time for figuring out complex linq queries when I know the sql approach I want to use.
VB http://msdn.microsoft.com/en-us/vbasic/bb688085
C# http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx
If you know how to write the sql query to get the data you want then this will show you how to get the same result translating it into linq syntax.
I have two datatables. One is a superset of another. Both have one column StageID common. I need to merge these two tables together so that the subset datatables data gets stored in the correct row of superset table.
This is what i did to join the data after retrieving the superset data in JoinTable and subset data in DTMaterialProperties table
foreach (DataColumn dcMaterialProp in dtMaterialProperties.Columns)
{
if (dcMaterialProp.ColumnName != "StageId" &&
JoinDataTable.Columns.Contains(dcMaterialProp.ColumnName))
{
JoinDataTable.Rows[rowCount][dcMaterialProp.ColumnName] =
dtMaterialProperties.Rows[0][dcMaterialProp.ColumnName];
}
}
But this was not efficient as it takes a lot of time in looping through.
Please Help me in finding a better way to do this.
If you can use LINQ, an easy way would be to use the Join extension method.
See Join Method-Based Query Syntax Examples (LINQ to DataSet)
If you don't have access to LINQ to DataSet
...you can check out this link from MSDN on how to implement a DataSet JOIN Helper Class.
HOW TO: Implement a DataSet JOIN helper class is Visual C# .NET
What you are really looking for seems to be a relationship. If you add both datatables to the same dataset, you can define the relationship. See Define a relationship between two tables in a DataSet in VB .NET
Then, all you have to do is parentRow.GetChildRows() to get the associated child rows.
I have a ASP.Net page using ADO to query MS access database and as a learning exercise i would like to incorporate LINQ. I have one simple table called Quotes.
The fields are: QuoteID, QuoteDescription, QuoteAuthor, QuoteDate. I would like to run simple queries like, "Give me all quotes after 1995".
How would i incorporate LINQ into this ASP.Net site (C#)
Basically, my question is does LINQ work for MS Access ??
LINQ to SQL doesn't support Access (that is, there's no Access/Jet provider for LINQ), but you can query a DataSet with LINQ. This means that you fill your DataSet with any possible data from your database that you might need in your results, and then you filter on the client side. After you have a typed DataSet, and you Fill() it with a TableAdapter, you do something like this:
var year = 1995; // you can pass the year into a method so you can filter on any year
var results = from row in dsQuotes
where row.QuoteDate > year
select row;
You'll have to decide whether this is worth it. You'd have to fill your DataSet with all the quotes, then use LINQ to filter on just those quotes that are after 1995. For a small amount of data, sure, why not? But for a very large amount of data, you'll need to make sure it won't be too slow.
If you're using a DataSet, though, you can write custom queries that become new TableAdapter methods. So you can put the correct SQL for your query in a FillByYear() method in your TableAdapter and use that to fill your typed DataTable. That way you're only getting back the data you need.
If you go this route, remember that Access/Jet uses positional parameters, not named parameters. So instead of
SELECT * FROM Quotes WHERE Year(QuoteDate) > #Year
you'd use something like this:
SELECT * FROM Quotes WHERE Year(QuoteDate) > ?
I don't think LINQ to SQL supports Access. However, if your table is sufficiently small to fit into memory, LINQ to DataSet will let you query datatables etc pretty easily - especially strongly typed datasets.