I am trying to learn and start using entity framework 5.0
I was able to create my data model (Only one table), but I am not able to find the commands / functions / methods that allow me to send sql queries and access the results and save and update...etc. Can someone write a very small block of code to show how to do so?
You can write raw SQL like so to return entities:
var entities = context.MyEntities.SqlQuery("SELECT * FROM dbo.MyEntities").ToList();
Or for non entities:
var myAttributeValues = context.Database.SqlQuery<string>(
"SELECT MyAttribute FROM dbo.MyEntities").ToList();
However, you should not use raw sql just because you prefer it. You should use it in situations where raw sql provides you with an advantage over generated queries. If you prefer to write SQL then you should reconsider whether you really want to use EF or any other ORM at all. See here for some EF documentation and examples and here for info on querying for entities.
Related
We are using DTOs server side, and have configured a dbcontext using fluent api in order to give breeze the metadata it needs. We map 1:1 to our real database entities, and each DTO contains a simple subset of the real database entity properties.
This works great, but now I need to figure out a way to make queries efficient - i.e. if the Breeze client queries for a single item I don't want to have to create a whole set of DTO objects before I can filter. i.e. I want to figure out a way to execute the filter/sort on the actual entities, but still return DTO objects.
I guess I need to figure out a way to intercept the query execution in order to query my real database entities and return a DTO instead of the real database entity.
Any ideas for how to best approach this?
Turns out that if you use projection in a link statement, e.g.
From PossibleCustomer As Customer
In Customers
Select New CustomerDto With {.Id = PossibleCustomer.Id,
.Name = PossibleCustomer.Name,
.Email = PossibleCustomer.Email}
.. then linq is smart enough to still optimize any queries to the database - i.e. if I query on the linq statement above to filter for a single item by Id, the database is hit with that query for just a single item and a single DTO is created. Pretty clever stuff. This only works if you do a direct projection in the linq statement - if you call off to a function to create your DTO then this won't work.
Just in case others are facing the same scenario, you might want to look at AutoMapper - it can create these projections for you using a model you create just once - avoids all those huge linq statements that are hard to read and validate. The automapper projections (assuming you stick to the simple stuff) still allow the linq to entities magic that ensures you don't have to do table scans when you create your DTOs.
We are using entity framework 6.0 for development of our new application. All of our entity queries are generated from a DAL layer. For our current applications that are deployed to production, we use a SQL monitoring tool to track the performance of SQL queries.
My concern is how will I track down the DAL class that is generating the SQL so, I can address performance issues with the entity query. All I have from the tool is the SQL query that was generated by entity framework.
How are others tracking down SQL query issues in production? I know I can use Glimpse but how can you track back to the entity framework query that generated the SQL if you just have the raw SQL? I tried using the predicate builder to add a dummy where clause to see if that would show up in the SQL but it is ignored. like
predicate = predicate.Or(u => "methodName" == "methodName");
Thanks for the help.
You could use New Relic to instrument the application and SQL. They have a feature called "Key Transactions" which can tell you the slow transactions (really set up just for web requests, but you can theoretically get it working for other types of apps) and allow you to see the slow SQL queries within those transactions.
In order to add your data access layer in to the methods being instrumented, you can edit the instrumentation xml files as per https://docs.newrelic.com/docs/dotnet/dotnet-agent-custom-metrics
Note that the Key Transactions feature is in the premium addition, which costs. You do get that free for a while, so it might be worth a look to see if it provides enough value to you.
(I have no affiliation with New Relic, by the way.)
If you have a test suite covering the code that generates the queries, you could use this to save the generated SQL queries out to file along with the DAL method that generated them. You could do this by using the following code (taken from this SO answer regarding viewing the SQL):
var result = from x in appEntities
where x.id = 32
select x;
var sql = ((System.Data.Objects.ObjectQuery)result).ToTraceString();
If you saved these queries and method names in some structured fashion (e.g. CSV), perhaps as a side effect of the test run, you might be able to do a reverse lookup by searching this file for the query you see from production. You might have to do some normalisation, e.g. strip out all non-significant whitespace and in both cases take out the parameter assignments.
I have always been using nhibernate ORM for inserting data to sql tables from application.
But recently I tried reading on Ado.net and found suggestion to use stored proc instead of
sqlcommand.executenonQuery().
In that case, every table insertion will need a different stored proc . A 100 table application will need 100 Stored procs. Is my understanding correct or is there a better way of doing it in a more generic way?
Please suggest.
A simple one-liner command can be an INSERT given directly in .NET code via parameterized Command class. Something like:
using (SqlConnection sqlConn = new SqlConnection(connectionString)) {
using (SqlCommand sqlCmd = new SqlCommand("INSERT INTO MyTable (Field1, Field2) VALUES (#Param1, #Param2)", sqlConn)) {
sqlCmd.Parameters.AddWithValue("#Param1", someValue1);
sqlCmd.Parameters.AddWithValue("#Param2", someValue2);
sqlConn.Open();
sqlCmd.ExecuteNonQuery();
}
}
So it doesn't have to be a stored proc for every command. You can have a class or classes dedicated to DB access only (db access layer) and populate it with various methods to read/write from DB. You can even have a generic method that automatically derives parameters for INSERT/UPDATE commands.
Of course if it's more than 1-2 commands or some logic is involved - that asks for a stored procedure.
Btw, this is my personal opinion, but i think ORMs are evil.
Have you heard about dapper, a powerful tool to execute a query and map the results to a strongly typed List. Dapper also support stored procedures, check this out.
Example:
dbConnection.Query<return type>("yourSP", parameters,
commandType: CommandType.StoredProcedure).First();
Also take some time to check this SO question.
Personally I would use an ORM if I have more than 5 different tables to select and/or insert into. Why should you walk 100 miles if the bus stop is right infront of the door?
That said the ORM is a generic way to access data. If you would want to code everything by hand, you could surely write stored procedures with optional parameters, but I don't recomend it.
I will start a new project in couple of days which is based on ASP.NET MVC3 and I don't have enough experience in Web Development.
I just want to know about Entity Framework. What is Entity Framework? Why we use it?
and also want to know about Object Relational Mapping. How is it connect with entity framework?
I've googled but did not get exact idea about it.
I'm very eager to know what's basic concept behind all those things?
Entity Framework is an object-relational mapper. This means that it can return the data in your database as an object (e.g.: a Person object with the properties Id, Name, etc.) or a collection of objects.
Why is this useful? Well, it's really easy. Most of the time you don't have to write any SQL yourself, and iterating is very easy using your language built in functions. When you make any changes to the object, the ORM will usually detect this, and mark the object as 'modified'. When you save all the changes in your ORM to the database, the ORM will automatically generate insert/update/delete statements, based on what you did with the objects.
In code, you might want to work with objects in an object oriented fashion.
MyClass obj = new MyClass(); // etc.
However, it might be cumbersome to save data to databases from objects, since you might end up with mapping your object to an SQL query string
// Perhaps with parameter bindings instead, but the idea is the same
"INSERT INTO MYTBL name,phone VALUES(" + obj.Name + "," + obj.Phone + ")";
An ORM framework does this object to SQL mapping by generating SQL statements and the Entity manager will execute them when you need to save or load objects from the database. It comes at the cost of another abstraction layer, but it will make the code easier to write.
So it turns out that I am the last person to discover the fundamental floor that exists in Microsoft's Entity Framework when implementing TPT (Table Per Type) inheritance.
Having built a prototype with 3 sub classes, the base table/class consisting of 20+ columns and the child tables consisting of ~10 columns, everything worked beautifully and I continued to work on the rest of the application having proved the concept. Now the time has come to add the other 20 sub types and OMG, I've just started looking the SQL being generated on a simple select, even though I'm only interested in accessing the fields on the base class.
This page has a wonderful description of the problem.
Has anyone gone into production using TPT and EF, are there any workarounds that will mean that I won't have to:
a) Convert the schema to TPH (which goes against everything I try to achieve with my DB design - urrrgghh!)?
b) rewrite with another ORM?
The way I see it, I should be able to add a reference to a Stored Procedure from within EF (probably using EFExtensions) that has the the TSQL that selects only the fields I need, even using the code generated by EF for the monster UNION/JOIN inside the SP would prevent the SQL being generated every time a call is made - not something I would intend to do, but you get the idea.
The killer I've found, is that when I'm selecting a list of entities linked to the base table (but the entity I'm selecting is not a subclass table), and I want to filter by the pk of the Base table, and I do .Include("BaseClassTableName") to allow me to filter using x=>x.BaseClass.PK == 1 and access other properties, it performs the mother SQL generation here too.
I can't use EF4 as I'm limited to the .net 2.0 runtimes with 3.5 SP1 installed.
Has anyone got any experience of getting out of this mess?
This seems a bit confused. You're talking about TPH, but when you say:
The way I see it, I should be able to add a reference to a Stored Procedure from within EF (probably using EFExtensions) that has the the TSQL that selects only the fields I need, even using the code generated by EF for the monster UNION/JOIN inside the SP would prevent the SQL being generated every time a call is made - not something I would intend to do, but you get the idea.
Well, that's Table per Concrete Class mapping (using a proc rather than a table, but still, the mapping is TPC...). The EF supports TPC, but the designer doesn't. You can do it in code-first if you get the CTP.
Your preferred solution of using a proc will cause performance problems if you restrict queries, like this:
var q = from c in Context.SomeChild
where c.SomeAssociation.Foo == foo
select c;
The DB optimizer can't see through the proc implementation, so you get a full scan of the results.
So before you tell yourself that this will fix your results, double-check that assumption.
Note that you can always specify custom SQL for any mapping strategy with ObjectContext.ExecuteStoreQuery.
However, before you do any of this, consider that, as RPM1984 points out, your design seems to overuse inheritance. I like this quote from NHibernate in Action
[A]sk yourself whether it might be better to remodel inheritance as delegation in the object model. Complex inheritance is often best avoided for all sorts of reasons unrelated to persistence or ORM. [Your ORM] acts as a buffer between the object and relational models, but that doesn't mean you can completely ignore persistence concerns when designing your object model.
We've hit this same problem and are considering porting our DAL from EF4 to LLBLGen because of this.
In the meantime, we've used compiled queries to alleviate some of the pain:
Compiled Queries (LINQ to Entities)
This strategy doesn't prevent the mammoth queries, but the time it takes to generate the query (which can be huge) is only done once.
You'll can use compiled queries with Includes() as such:
static readonly Func<AdventureWorksEntities, int, Subcomponent> subcomponentWithDetailsCompiledQuery = CompiledQuery.Compile<AdventureWorksEntities, int, Subcomponent>(
(ctx, id) => ctx.Subcomponents
.Include("SubcomponentType")
.Include("A.B.C.D")
.FirstOrDefault(s => s.Id == id));
public Subcomponent GetSubcomponentWithDetails(int id)
{
return subcomponentWithDetailsCompiledQuery.Invoke(ObjectContext, id);
}