In short: can I use a literal SQL subquery somehow in the entity model without using database views?
Context: I have a bunch of ADO.NET queries that result in C# objects. These objects correspond directly to the query shape; i.e. I can do ObjectContext.Translate to extract them from the SqlDataReader. There are lots of these queries, many quite complex, and some of which use features the entity framework doesn't support (while loops, CTE's, hierarchyids, etc.) - converting these (legacy) queries to LINQ isn't feasible.
However, I'd really like to be able wrap these results and add some custom filtering on the C# side of things: things like sorting, filtering, paging etc. I could convert each and every query into a view (or stored procedure) and map these, but that's a hassle and a maintenance nightmare - but in principle EF can be used with "opaque" SQL queries by that route.
Can I somehow use subqueries written in SQL with the entity model? An ObjectContext.Translate that returns an IQueryable rather than an IEnumerable would be ideal, but not necessary: the vast majority of queries are compile-time constants, so some form of pre-processing is possible.
Edit: I'm looking for something returning an IQueryable so I can add filters/sorting client side but have them executed on the DB (as usual). I'm using Entity Framework code-first.
You can set the DefiningQuery property of an EntitySet to some literal SQL. These are more or less equivalent to a SQL view. Does that solve your issue?
http://msdn.microsoft.com/en-us/library/cc982038.aspx
If your SQL query is giving a result with the same structure as of the entity class, you can use the DbContext.SqlQuery
var customer=context.Database.
SqlQuery<Customer>("SELECT ID,NAME from CUSTOMER WHERE TYPE IN
(SELECT TYPEID FROM IMPORTANT_TYPE)");
Assuming context is your DBContext class object
Related
I personally like SQL, but I realize I probably need to follow the EF design. At times and with other team members, SQL will be used. When a Raw SQL Query is made, does it return objects/properties for my C# code? If I have five tables mapped, and I do a raw query, are corresponding properties returned?
The answer is yes. You need to define your entity class for the result of your raw SQL Query, remember to make the name of the properties exactly the same with the name of returned columns in your query.
context.Database.SqlQuery<YourEntity>("your query").ToList();
With EF, you have to create and maintain the POCO for your raw query, and your query text will probably languish inside double quotes somewhere. Why not grab QueryFirst? Your sql will be in .sql file, and the wrapper code, including POCO will be generated and managed for you. And there are numerous other advantages!
You don't have to use one approach exclusively. Lots of folk use EF, then Dapper or something like it when they need/want to "revert" to SQL. QueryFirst isn't an ORM and doesn't replace EF. Obviously if you let EF manage your schema, (code first, model first) then non-EF queries risk being walloped by EF schema changes. But with QueryFirst at least, you can "recompile" your queries to assure they're working and still return what you need after EF has changed your schema.
Disclaimer: I wrote QueryFirst.
If EDM for 3 Tables is as shown in figer given below.
then,
is it good approach to use such foreign keys in EDM and in DB ?
can such DB design slower down execution ?
which architecture will be preferable with use of foreign key or
without use of foreign key ?
if any one want data from table-3 from id of TAble-1
then it can be done in 2 ways.
I.
db.TAble_1.FirstOrDefault(m => m.TAble_1ID == 2).Table_2.FirstOrDefault().TAble_3;
II.
By Join in LINQ
So which one is faster ?
if any one want data from table-1 from id of TAble-3
then it can be done in 2 ways.
I.
db.TAble_1.FirstOrDefault(m => m.TAble_3ID == 2).Table_2.TAble_3;
II.
By Join in LINQ
So which one is faster ?
Thank You all ,in advance.
Nope, Basically what is EDM or Lets take an example of Linq to Sql, It is just a converter of your Object Queries to SQL, and then it fires the same as the Inline query , using a SqlConnection object.
This Question is two - fold :
Is the Database Design Proper? - Coz this is actually going to Make a Difference in the Performance. Design makes the Core of the Queries, its refining can take care of most of your Performance issues.
EDMX , Linq To Sql, Entity Framework or some other ORM (Object Relational Mappers) : Normally why would one use a ORM? Since they have small queries and they are not very proficient into SQL Server, or they want the Learning curve for the Developers to be blunt comparatively, and need to right the simple small queries at their ease and pretty Rapidly (Having a Stored procedure for a Simple Select doesnt make sense.) So it solves your problems by Converting your Object Queries (LINQ) to Sql statements.
Answer for your Case:
It depends on for which queries you use the same, The queries which you have stated it wont make difference if it has joins, (Considering your Design is proper.) EDM , or anything stated above is fine for any of such queries,
But yes dont use it for "TOO BIG QUERIES" or dont Replace Stored Procedures with this since what happens is it converts your Object queries to SQL statements, sends it to the DB Server , Sql Server Engine parses the Queries, and then Executes; So in case the Queries are too big then in that case the Network Latency, Compilations of the Queries, (& since the Queries are just being Compiled it doesnt compile the Execution plan.) whereas in case of Stored Procedures it is already there and the Queries run pretty faster
Useful links:
Execution Plan
I am working on window application developed using SCSF and we are using sybase database. As practise we create typedataset in the .net project and then populate them using framework method and for all the sql statement we write stored procedure in the database.
So we have type dataset in memory so I am using linq to select records from datatable. Can I step one step further and use something related to Entity Framework?
Can it reduce my work? I don't have hands-on experience with Entity Framework but can you suggest something in this scenario?
Thanks,
Denish
Entity framework uses similar concepts as the type datasets except for:
The ability to have a class structure that is not exactly the same as the table structure (e.g. class hierarchy, splitting tables into multiple classes, joining tables into one class).
The ability to use LINQ to perform queries in the database instead of in memory.
Entity framework also lets you map results of stored procedures to classes and bring results into memory if you need to run a query that is faster in memory or not translatable to SQL.
For most SQL queries the LINQ to Entity will be effective enough, so you will probably end up writing less stored procedures.
You will have to learn how to use EF and LINQ effectively and use can use 3rd party tools such as Entity Framework Profiler to help you.
I am working on a piece of functionality where a user may select multiple parameters with multiple values in each parameter. I am trying to figure out a way to design this functionality in my application using C#, entity framework with entities being mapped to stored procedure. Due to security reasons, my application has to access the database via a surrogate database which has only stored procedures. Therefore my entities are mapped to stored procedures for insert, update, and select.
Ultimately, I need to pass the filters chosen by the user to the stored procedure for querying the database. One of the solutions I thought of is to retrieve all the data to my business layer and use linq to filter out further. But this is not ideal due to the amount of data being filtered in the memory rater than in the database which is more better suited to do this kind of complex query.
I have seen posts for constructing dynamic queries with linq, but in these kind of posts, the entities are mapped to the tables which makes it easier.
Any help here will be greatly appreciated.
Thank You,
sirkal
EF (and LINQ for that matter) use deferred execution. You can fairly easily create a dynamic query using IQueryable (Google search time?) and creating the filter criteria in an object you build (you can do it without the object, but think reusable).
As for the SQL sproc, you can also solve it there by passing in all of the items that can possibly change the filter and having SQL dynamically work on the data to produce a result set.
Which to choose? It really depends on where the core competency is in your group. I prefer C# code mostly due to familiarity (spent years doing sprocs, but dynamic sprocs can be a royal pain).
Now, one thing you do want to be wary of is ending up with dynamic queries that cannot easily be tuned by the server (like statistics in SQL Server, although other RDBMSes use similar concepts). One issue I have seen with LINQ to SQL, for example, is dynamic queries that cause SQL to perform less than optimally, requiring a lot of handholding from the DBA.
A bit of a clarification: I was browsing Julia Lerman's Oreilly title on Entity framework and I got mighty confused.
I have Charlie Calvert's essential LINQ, but from my 10 minute session with Lerman's book, it transpires that LINQ is LINQ to SQL which seems underpowered with its DataContext object etc...
Whereas Entity Framework is the future, but it has something called Entity SQL which to my eye looked exactly like Transact-SQL. Now my eye could be a bit rusty, but the question is:
Since Entity Framework is the main horse that Microsoft is backing, is there any point in learning LINQ to SQL with its
var numberGroups =
from n in numbers
group n by n % 5 into g
select new { Remainder = g.Key, Numbers = g };
And am I confused in thinking that Entity SQL and LINQ are two different technologies, does entity SQL in fact use LINQ?
post the many replies I got:
Ok Folks, I'm new to this, so I'm editing my answer this time ;-)
Many thanks for your full, expedited and very helpful answers.
Regards
MereMortal
LINQ != LINQ-to-SQL
LINQ is the concept, including some language support. There are many implementations - LINQ-to-SQL is one, as is ADO.NET Data Services, Entity Framework's LINQ-to-Entities, LINQ-to-Objects, LINQ-to-SQL, LINQ-to-Amazon, DbLinq, etc.
You still use LINQ with Entity Framework; indeed, LINQ-to-Entities is the preferred choice, giving compile time static checking. Entity SQL is simply another mechanism (in addition to LINQ-to-Entities) for querying the EDM (Entity Data Model).
There are 3 main reasons that ESQL is useful:
it was the only option in early previews when LINQ-to-Entities was still under construction
it can be used in some scenarios where there is no object model, for example reporting services
there is a small number of cases where ESQL is more expressive
For everything else, LINQ should be your tool for working with Entity Framework.
LINQ is a generic term for the language features that permit queries to be written in C# or VB.NET over a data store of some sort. There is LINQ to SQL, LINQ to Entities, LINQ to Objects, etc.
LINQ to SQL closely models the physical database structure. It produces one type for every table in the database. If your database changes, then your LINQ to SQL code will need to change.
LINQ to Entities more closely models the conceptual database design. It allows you to map to the physical database, but for instance, allows you to create one Person entity that includes data from both the Person and Contacts tables. This allows your callers to think in terms of what the data mean instead of how the data are implemented.
Also, Microsoft has said that future development in LINQ to SQL will be limited when compared to the development in LINQ to Entities. Given the increased flexibility and the fact that LINQ to SQL won't get many more enhancements, I'd go with LINQ to Entities and Entity Framework.
As others said, you probably mean Linq to SQL vs Entity Framework.
Both work for SQL Server, but only Entity Framework will work for other databases. Also, LINQ to SQL has, more or less, been depreciated. So go with Entity Framework.
Linq is a programming construct that allows you query your objects
there is a Linq to Sql that I think you are talking about.
you can always use linq to query EF objects...
Whoa whoa. Slow down there.
Short Answer: Entity Framework
Longer Answer:
LINQ to SQL and Entity Framework are data access technologies.
Linq is, according to MS,
LINQ is a set of extensions to the .NET
Framework that encompass
language-integrated query, set, and
transform operations. It extends C#
and Visual Basic with native language
syntax for queries and provides class
libraries to take advantage of these
capabilities.
from : http://msdn.microsoft.com/en-us/netframework/aa904594.aspx
Both LINQ to SQL and Entity Framework have Linq providers, which allow for that awesome syntax when querying against them.
Entity Framework has LINQ to Entities, so you can execute very the same query against EF as well. And my answer will be invest more to EF, because upcomming EFv4 seems promissing.
From what I understand, EF is not quite ready for prime time yet, and it does not support many of the LINQ constructs that work so easily today in LINQ2SQL.
If you can commit to SQL Server for your application, I say today, learn LINQ2SQL. You'll have more capabilities in querying when using LINQ.
I'm betting when EF is ready, it'll be a much easier transition for you since the query language should be transferrable.
Good luck.
I go in microsoft TehcDays in Montreal on december 2 and 3, and they said, that they will no longer support LINQ to sql in few year, so your better start to learn LinQ to entity (Entity framework).