Entity SQL doesn't work if edmx file in another project - entity-framework

I'm trying to use Enitity SQL to query data, but if the edmx file in another project, there will be an exception thrown. Below is my test steps.
Create a Class Library project and add an edmx file to it, create from database.
Create a Console Application, add the Class Library project to reference and copy the app.config file to this project.
Write the code as below
using (NorthwindEntities context = new NorthwindEntities())
{
string queryString = #"SELECT VALUE cus
FROM NorthwindEntities.Customers AS cus
WHERE cus.ID > 10";
ObjectQuery<Customers> cusQuery =
context.CreateQuery<Customers>(queryString);
List<Customers> cusList = cusQuery.ToList();
}
When I run the Console Application project, an exception is thrown: "'ID' is not a member of type 'NorthwindModel.Customers' in the currently loaded schemas."
It seems the schema doesn't loaded into the project, anyone has ideas?
Addional question: in this query, I select all the properties of this type, if I only select some of the properties, how to return an anonymous type of ObjectQuery?
Any suggestions are appreciate.

This is not an EF problem.
You have written the SQL statement by hand, you are not using the table definition that is in the EDMX file.
If you try to execute the SQL statement in the Query prompt of SQL Server, you will see that it fails there as well.
Try something like this:
var cus = from customers in context.Customers select customers;
var cusList = cus.ToList();

Related

Modified Entity Workspace is ignored when generating SQL

I have an Entity Model (EDMX) file and EF 4.3.1. I am trying to make a run-time modification to the EDMX (change the store:Schema of the tables/entitySets used in generating the query). I am using code based on the EF Model Adapter project by B. Haynes.
It appears that I can make the changes to the XML just fine using the schema model adapter, and load it into a metadata workspace and then pass it to the connection. However, when the query is generated by the DbContext/EF framework code, it uses the old value for the schema.
Create a new MyEntities
Load the EDMX medata data manually
Replace the "store:Schema" value with the new desired value
Create the metadata workspace from the modified XML
Return a new EntityConnection using that modified workspace
Query the data (from x in db.Table select x)
This is the basics of what is going on. We create our dbContext by creating a new EntityConnection based on the modified workspace and the connection. There is also some provider wrapping and such going on, for logging, etc. Sorry if that's confusing.
public MyEntities(): base( this.Create("name=MyEntitiesConnStr"), true)
{
}
public static DbConnection Create(string connectionString)
{
var ecsb = ConnectionHelper.ResolveConnectionStringDetails(connectionString);
var workspace = GetModifiedEntityWorkspace(ecsb);
var storeConnection = DbProviderFactories.GetFactory(ecsb.Provider).CreateConnection();
Debug.Assert(storeConnection != null, "storeConnection != null");
storeConnection.ConnectionString = ecsb.ProviderConnectionString;
var wrappedConnection = MyWrappedConnetion.WrapConnection(storeConnection);
_log.Debug("Creating new entity connection");
var newEntityConnection = new EntityConnection(workspace, wrappedConnection);
WireEvents(wrappedConnection);
return newEntityConnection;
}
private static MetadataWorkspace GetModifiedEntityWorkspace(EntityConnectionStringBuilder ecsb)
{
// instantiate manager class
// read all XML items from the embedded resources
// change the store:schema to the real one for this environment
// <EntitySet Name="..." store:Type="Tables" store:Schema="SCM" store:Name="TBLX">
// create new MetadataWorksspace(ssdl,cdl,...)
}
Any idea where/why it is still getting the old Schema value for the query? I think it worked right with EF 4.0,
Turns out the problem was with the <DefiningQuery> element under the entity set.
This element contains a definition of the base query used to define the entity. Perhaps something changed and now they refer to that for speed reasons. It is necessary to modify that query as well, and then the schema change will take effect.
<EntitySet Name="MYTABLE" store:Type="Tables" store:Schema="MYSCHEMA" ...>
<DefiningQuery>
SELECT MYTABLE.COLUMN [...REPEAT..]
FROM MYSCHEMA.MYTABLE AS MYTABLE
</definingQuery>
So, changing "MYSCHEMA" in both those locations fixes it. Just the store:Schema element is not enough.

MVC 4 project using a class library EF model

Using an EF model in the Models folder in my MVC 4 project, I succeeded to display data in a razor view using a coded class named Prod and a controller method as next:
public ActionResult Index()
{
IEnumerable<Prod> Pr = from p in db.Products
select new Prod
{
ProductId = p.ProductID,
ProductName = p.ProductName
};
return View(Pr);
}
Now I am trying to do the same thing using a model in a class library instead of the current one, so I added to my solution a new class library, added then a model using the same connection string, and mapping the same entities, then added to my MVC project a reference to the new class library, and put at the top of both MyController and Prod class the next:
using MyClassLibrary;
Then I deleted the old model, now when I try to display the view, I get the following error:
Unable to load the specified metadata resource.
Any help please ?
When you move or rename the project the data context (.edmx) is in the metadata part of the Entity Framework connection string has to change
you can try have
connectionString="metadata=res://*/MyModel.csdl|res://*/MyModel.s‌​sdl|res://*/MyModel.msl;
instead of
connectionString="metadata=res://*/Models.MyModel.csdl|res://*/Models.MyModel.s‌​sdl|res://*/Models.MyModel.msl;
or try deleting your context and recreating it then check the connection string it adds automatically.
You need to put your connectionstring in web.config in Mc4 web project
You need to Mention the datasource in the connection string.
If you have not used any other web.config file for views. Use you generic web.config file and upload a connection string with New datasource name , user and password.

How can I override SQL scripts generated by MigratorScriptingDecorator

Using Entity Framework 4.3.1 Code first, and Data Migrations.
I have written a utility to automatically generate the Migration scripts for a target database, using the MigratorScriptingDecorator.
However, sometimes when re-generating the target database from scratch, the generated script is invalid, in that it declares a variable with the same name twice.
The variable name is #var0.
This appears to happen when there are multiple migrations being applied, and when at least two result in a default constraint being dropped.
The problem occurs both when generating the script form code, and when using the Package Manager console command:
Update-Database -Script
Here are the offending snippets form the generated script:
DECLARE #var0 nvarchar(128)
SELECT #var0 = name
FROM sys.default_constraints
WHERE parent_object_id = object_id(N'SomeTableName')
and
DECLARE #var0 nvarchar(128)
SELECT #var0 = name
FROM sys.default_constraints
WHERE parent_object_id = object_id(N'SomeOtherTableName')
I would like to be able to override the point where it generates the SQL for each migration, and then add a "GO" statement so that each migration is in a separate batch, which would solve the problem.
Anyone have any ideas how to do this, or if I'm barking up the wrong tree then maybe you could suggest a better approach?
So with extensive use of ILSpy and some pointers in the answer to this question I found a way.
Details below fo those interested.
Problem
The SqlServerMigrationSqlGenerator is the class ultimately responsible for creating the SQL statements that get executed against the target database or scripted out when using the -Script switch in the Package Manager console or when using the MigratorScriptingDecorator.
Workings
Examining the Genearate method in the SqlServerMigrationSqlGenerator which is responsible for a DROP COLUMN, it looks like this:
protected virtual void Generate(DropColumnOperation dropColumnOperation)
{
RuntimeFailureMethods
.Requires(dropColumnOperation != null, null, "dropColumnOperation != null");
using (IndentedTextWriter indentedTextWriter =
SqlServerMigrationSqlGenerator.Writer())
{
string value = "#var" + this._variableCounter++;
indentedTextWriter.Write("DECLARE ");
indentedTextWriter.Write(value);
indentedTextWriter.WriteLine(" nvarchar(128)");
indentedTextWriter.Write("SELECT ");
indentedTextWriter.Write(value);
indentedTextWriter.WriteLine(" = name");
indentedTextWriter.WriteLine("FROM sys.default_constraints");
indentedTextWriter.Write("WHERE parent_object_id = object_id(N'");
indentedTextWriter.Write(dropColumnOperation.Table);
indentedTextWriter.WriteLine("')");
indentedTextWriter.Write("AND col_name(parent_object_id,
parent_column_id) = '");
indentedTextWriter.Write(dropColumnOperation.Name);
indentedTextWriter.WriteLine("';");
indentedTextWriter.Write("IF ");
indentedTextWriter.Write(value);
indentedTextWriter.WriteLine(" IS NOT NULL");
indentedTextWriter.Indent++;
indentedTextWriter.Write("EXECUTE('ALTER TABLE ");
indentedTextWriter.Write(this.Name(dropColumnOperation.Table));
indentedTextWriter.Write(" DROP CONSTRAINT ' + ");
indentedTextWriter.Write(value);
indentedTextWriter.WriteLine(")");
indentedTextWriter.Indent--;
indentedTextWriter.Write("ALTER TABLE ");
indentedTextWriter.Write(this.Name(dropColumnOperation.Table));
indentedTextWriter.Write(" DROP COLUMN ");
indentedTextWriter.Write(this.Quote(dropColumnOperation.Name));
this.Statement(indentedTextWriter);
}
}
You can see it keeps track of the variables names used, but this only appears to keep track within a batch, i.e. a single migration. So if a migratin contains more than one DROP COLUM the above works fine, but if there are two migrations which result in a DROP COLUMN being generated then the _variableCounter variable is reset.
No problems are experienced when not generating a script, as each statement is executed immediately against the database (I checked using SQL Profiler).
If you generate a SQL script and want to run it as-is though you have a problem.
Solution
I created a new BatchSqlServerMigrationSqlGenerator inheriting from SqlServerMigrationSqlGenerator as follows (note you need using System.Data.Entity.Migrations.Sql;):
public class BatchSqlServerMigrationSqlGenerator : SqlServerMigrationSqlGenerator
{
protected override void Generate
(System.Data.Entity.Migrations.Model.DropColumnOperation dropColumnOperation)
{
base.Generate(dropColumnOperation);
Statement("GO");
}
}
Now to force the migrations to use your custom generator you have two options:
If you want it to be integrated into the Package Manager console, add the below line to your Configuration class:
SetSqlGenerator("System.Data.SqlClient",
new BatchSqlServerMigrationSqlGenerator());
If you're generating the script from code (like I was), add a similar line of code to where you have your Configuration assembly in code:
migrationsConfiguration.SetSqlGenerator(DataProviderInvariantName,
new BatchSqlServerMigrationSqlGenerator());

Create and User User Define Function in edmx

i want to create one function in edmx which return scaler value,
how to create it in SSDL and how to access it in code?
One problem you have is your SSDL is automatically generated by the 'EntityModelGenerator', so editing it will be wiped out by a rebuild. Your edits need to be done in th EDMX file.
So firstly, you have to decide is (1) your return value a calculation of sorts (i.e. adding values together in the application, rather than at database level), or (2) is it a direct call to a database stored procedure?
(1) First step is to add the function XML definition into your EDMX file:
<Function Name="LineTotal" ReturnType="decimal">
<Parameter Name="lineTotal" Type="MyDbModel.OrderDetail">
<DefiningExpression>
od.Price * od.Quantity
</DefiningExpression>
</Parameter>
</Function>
Now, although your EDMX knows about this function, your IntelliSense won't. So you have to add some code to make this work. It is a best practice to place these functions in a seperate class.
public class ModelDefinedFunctions
{
[EdmFunction("MyDbModel" , "LineTotal")] //Model Name and Function Name
public static decimal LineTotal(OrderDetail od)
{
throw new NotSupportedException("LineTotal cannot be directly used.");
}
}
Entity Framework will know to redirect this function call to the EDMX instead. Any direct call to this method, where the model does not exist will throw an exception.
You can then call it in your LINQ queries like
var productValues = from line in model.OrderDetails
select new
{
od.ProductID,
od.Price,
od.Quantity,
LineTotal = ModeDefinedFunctions.LineTotal(line)
};
(2) If you are adding a stored procedure directly, it is easier to drag and drop it onto the EDMX designer. There is a [FunctionImport()] attribute, but I haven't used it. You can drag and drop and see what code it generates in the EDMX file?
Alternatively, you can call the model.ExecuteCommand(<spname> , params object[] values
) stored procedure execution method.

Can not find out the function for stored procedure in Entity Framework

Based on a database myDB, I generate edmx for all table and compile the project. Then I create stored procedure myProc in myDB. Then I update the model by "Update Model from database" in the node Stored Procedure and add myProc. It is fine. Then "Create a function import" on myProc. It is fine. Then I compiled the project, it is fine.
The return type for this import function is scalars(string) because myProc return a string.
Then I want to use this function for this stored procedure, but I can find out the function.
How to find out the matching function and call it in code?
In EF 3.5 only functions that return Entities show up in ObjectServices.
I.e. importing pulls the Function into the Conceptual Model, but NOT into the code-generation.
We have addressed this problem in 4.0.
In the meantime you can call the function using eSQL.
i.e. something like this (pseudo code):
EntityConnection connection = ctx.Connection as EntityConnection;
//Open the connection if necessary
connection.Open()
//Create the command
EntityCommand command = new EntityCommand();
command.CommandText = "Function(#p1,#p2");
command.Parameters.Add(...);
command.Parameters.Add(...);
command.Connection = connection;
string s = command.ExecuteScalar().ToString();
Hope this helps
Alex