Embed Custom SQL with Entity Framework - entity-framework

From what I have looked at so far, I am guessing the answer to this question is "no" but I thought I would ask in the event that I am missing something.
I have looked at the new RLS (row-level security) feature of Azure SQL. One of the things that needs to be done is to set the (user) context before executing a SQL statement. Since I am also looking at entity framework, my question is whether or not I can embed or inject something like "EXECUTE AS USER = 'User1'" into the SQL that is generated by entity framework.
Is this something that is possible? I know I can execute custom SQL but I was looking to set the code up in one place and have it run the statement for all generated SQL.

may be this EF6 feature can help, and more particularly the interception interface by the IDbCommandInterceptor.
Not clear about the hability to change the generated sql but may be.
Otherwise, have you tried a context.Database.ExecuteSqlCommand("EXECUTE AS...") ?

Create a new connectionstring using the user if you need to, or, you can modify the connectionstring used by DbContext.

Related

Entity Framework Code First with an existing database

I have to create a new project and (as usual) is with an existing SQL Server database.
I used to use EF Code First connecting with my database, opening my EDMX model designer and then right click --> Add Code Generation Item. (http://weblogs.asp.net/jgalloway/archive/2011/02/24/generating-ef-code-first-model-classes-from-an-existing-database.aspx) Easy.
But now I've discovered there's something called EF Power Tools that allows me to do Reverse Engineer Code First (cool name!) and get the same (http://msdn.microsoft.com/en-us/data/jj200620)
Do you know the difference between the two options? Which one is better?
Thanks in advance.
(Sorry if this question was previously asked but I didn't find it.)
The difference is that the edmx approach is not code first, but database first with DbContext API. You will always use the database as the source of model changes.
EF Power Tools produce a truly code first model with DbContext: from then on you will change the class model first and modify the database accordingly (e.g. by EF migrations).
Neither is "better". DbContext API is easier to work with than ObjectContext, but both approaches use the former. It's up to you to choose whether you want to work database first or code first. It's a matter of personal preference and it may depend on who maintains the database structure. With database first it is easier to respond to changes someone else imposes on the database structure.
As far as workflow goes for database first, adding to what #Gert-Arnold said:
With database first it is easier to respond to changes someone else imposes on the database structure.
If someone else is managing the database changes, I'm finding it far easier to use the EF Designer. You get an updated database, then just right-click in the EF Designer and update the model from the database. You can use source control to easily view what has changed.
Also, if you only need a subset of tables from the database, reverse engineering causes alot of work having to go back and remove classes and properties from the context.
I found re-reverse engineering via code-first to an existing database to be just too much of a pain trying to figure out what changed and how I needed to update code that used the context.

How to view generated SQL from Entity Framework?

As the title says, how do I view the SQL generated by Entity Framework from within my code? I'm running into an error where the EF is crashing because a field is generated by the database (a DateTime field), and I thought I set it to know that the store is generating it via StoreGeneratedPattern, but it's still crashing, so I would like to see what exactly it's trying to push up to the database.
P.S. I've only been using EF for about an hour now... Switching from L2S.
Since you don't have Sql Profiler, your best choice would be LINQPad. You can use your existing assembly.
Click Add connection -> Use a typed data context from your own assembly -> Entity framework and select your dll.
You can write queries directly against your model (or copy-paste from your code). Select the SQL 'tab' under the query window to view the generated SQL code.
You can use the Entity Framework Profiler (EFProf). It's not free, but there's a 30-day trial available. It does a lot more neat stuff besides showing you the SQL statements.
Generally, you should always use SQL Profiler to see the SQL statements that being submitted by EF into your database.
Also, I think you misunderstood about what StoreGeneratedPattern is. If you look at its possible values inside the model, you'll see that it has identity meaning that the value will be generated (by the database) when the row is inserted and will not otherwise change. The other options are Computed, which specifies that the value will be generated on inserts and updates, and None, which is the default.
So EF will not generate that DateTime field on the fly for you, you need to manually create it and then update your model from database so that EF will generate appropriate metadata to work with it at runtime.
The free AnjLab Sql Profiler will work if real SQL Profiler is not available because you're using SQL Server Express: http://anjlab.com/en/projects/opensource/sqlprofiler. It's not quite as nice as the real thing but it gets the job done well enough.
One solution would be to capture the network traffic and have a look at the data on that level. Microsoft Network Monitor does a good job of this.
Of course, that only works if you're using a separate DB server, and the connection is not encrypted.

Linq To SQL vs Entity Framework Connection Strings

Thanks for taking a look at my post.
I've been working with linq to sql and have generally been happy, until i just noticed that database table names are hardcoded into the classes/dbml files-- which can't work in our environment. We need to be able to have database names completely changeable via web.config-- in one place. That's a definite requirement.
Do you know how this can be achieved with Linq To Sql? If not, does the Entity Framework behave in the same manner? Perhaps i will have to port my model.
Appreciated!
In other words, i need "Tourism_DB" in the DataContext file:
[System.Data.Linq.Mapping.DatabaseAttribute(Name="Tourism_DB")]
public partial class TourismDataContext : System.Data.Linq.DataContext
{
as well as this text in the dbml
<Database Name="Tourism_DB" Class="TourismDataContext" xmlns="http://schemas.microsoft.com/linqtosql/dbml/2007">
to NOT be used, and the value in the web.config to be used anyway.
http://weblogs.asp.net/rajbk/archive/2008/05/20/connection-strings-in-linq-to-sql-classes.aspx
note you can do this with LINQ to SQL:
Dim c As New MyClassesDataContext(ConfigurationManager.ConnectionStrings("ConnectionString1").ToString())
The method i found here worked the best http://msmvps.com/blogs/superska/archive/2009/03/13/linq-to-sql-connectionstring-in-web-config.aspx. It laid out the full process.

Entity Framework equivalence for NHibernte SchemaExport

Is there an equivalence in Entity Framework to NHibernate SchemaExport?
Given I have a working Entity-Model, I would like to programmatically initialize a database.
I would like to use this functionality in the setup of my integration tests.
Creating the matching DDL for an Entity-Model would also suffice.
Yes - given that you're working with Entity Framework 4 (which is, confusingly enough, the second version...)
Edit: This is the way to do it with just EF4. In my original post below is described how to accomplish the same thing with the Code-Only approach in EF CTP3.
How to: Export model to database in EF4
To export a model to database, right-click anywhere in the designer (where you don't have an entity) and choose "Generate database from model..." and follow the steps described in the wizard. Voila!
Original post, targeting EF4 CTP3 and Code-Only: This is code I use in a little setup utility.
var builder = new ContextBuilder<ObjectContext>();
// Register all configurations you need here
builder.Configurations.Add(new EntryConfiguration());
builder.Configurations.Add(new TagConfiguration());
var conn = GetUnOpenedSqlConnection();
var db = builder.Create(conn);
if (db.DatabaseExists())
{ db.DeleteDatabase(); }
db.CreateDatabase();
It works on my machine (although here I've simplified a little bit for brevity...), so if something does not work it's because I over-simplified.
Note that, as TomTom stated, you will only get the basics. But it's pretty useful even if you have a more complicated schema - you only have to manually write DDL to add the complicated stuff onto the generated DB schema.
Nope, and seriously I do wonder why nhibernate bothers having this.
Problem is: an O/R mapper has LESS information about the database than needed for non-trivial setups.
Missing are:
Indices, fully configured
Information about server side constraints, triggers (yes, there may be some)
Information about object distribution over elements like table spaces
Information about permissions
I really love a test method (please check that database is good enough for all objects you know), but generation is VERY tricky - been there, done that. You need some serious additional annotations in the ORM to be able to even generate sensible indices.

Entity framework: ObjectContext get generated SQL change script?

Is there a way to get all the SQL change script of the object context?
Note: I am not talking about ObjectQuery.ToTraceString();
No unfortunately there isn't anything 'in' the product and available directly off the ObjectContext.
However you should take a look at Jarek's TracingProvider, that injects a layer between the EF and SqlClient to do logging etc.
Read about it here.