MVC 4 project using a class library EF model - entity-framework

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.

Related

Connection string for Entity Framework in an Azure Function

I'm creating an Azure Function and I've added a reference to a project that uses Entity Framework. I've copied the connection string from that project and pasted in the local.settings.json file inside the ConnectionStrings object as a valid EF connection string.
metadata=res://*/xxx.csdl|res://*/xxx.ssdl|res://*/xxx.msl;
provider=System.Data.SqlClient;
provider connection string=&quote;
data source=xxx;
initial catalog=xxx;
user id=xxx;
password=xxx;
MultipleActiveResultSets=True;
App=EntityFramework
&quote;
But it's given me this exception:
Keyword not supported: metadata.
If I use a valid SQL connection string (like below),
data source=xxx;
initial catalog=xxx;
user id=xxx;
password=xxx;
MultipleActiveResultSets=True;
App=EntityFramework
I've this exception:
The context is being used in Code First mode with code that was generated from an EDMX file for either Database First or Model First development. This will not work correctly. To fix this problem do not remove the line of code that throws this exception. If you wish to use Database First or Model First, then make sure that the Entity Framework connection string is included in the app.config or web.config of the start-up project. If you are creating your own DbConnection, then make sure that it is an EntityConnection and not some other type of DbConnection, and that you pass it to one of the base DbContext constructors that take a DbConnection. To learn more about Code First, Database First, and Model First see the Entity Framework documentation here: http://go.microsoft.com/fwlink/?LinkId=394715
How could I create a connection to my database in an Azure function using Entity Framework? I'm using .NET framework and for EF I'm using database first.
I'm init my database context as follow:
using (XxxDB db = new XxxDB())
{ }
Meanwhile, I've created an overload for the contrustor XxxDB
public XxxDB(string connectionString): base(new EntityConnection(connectionString), true)
{ }
And pass the SQL connection string when creating the XxxDB and got this error:
Keyword not supported: data source.
Ok, this is caused by how EF model first connection strings are generated. The EF connection string builder requires a plain connection string in the constructor. Then you add the metadata section for model first.
When you create new connection string to pass to a DB context string builder, change this:
public XxxDB(string connectionString): base(new EntityConnection(connectionString), true)
{ }
to
public XxxDB(string connectionString): base(GetEntityConnection(connectionString), true)
{ }
private static string GetEntityConnection(string connectionString)
{
var efConnection = new EntityConnectionStringBuilder();
efConnection.ProviderConnectionString = connectionString;
// res://*/xxx.csdl|res://*/xxx.ssdl|res://*/xxx.msl
var model = "xxx";
// this is what's missing in your question
efConnection.Metadata = string.Format("res://*/Model.{0}.csdl|res://*/Model.{0}.ssdl|res://*/Model.{0}.msl", model);
return efConnection.ConnectionString;
}

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.

Entity framework connection string reference from another project

I have a solution consisting of 4 projects. MVC, WCF, Business LYR, DataAcess. I am using entity framework for database transaction. My requirement is that i want to fetch the entity connectionstring only from MVC webconfig without refering in APP.cofig of acess layer. Is it possible in this scenario?
While I tried the following code I got an error.
this.ConnectionString="data source=cmh-sosql;initial catalog=Student;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework";
System.Data.SqlClient.SqlConnectionStringBuilder scsb = new System.Data.SqlClient.SqlConnectionStringBuilder(this.ConnectionString);
EntityConnectionStringBuilder ecb = new EntityConnectionStringBuilder();
ecb.Metadata = "res://*/schoolModel.csdl|res://*/schoolModel.ssdl|res://*/schoolModel.msl";
ecb.Provider = "System.Data.SqlClient";
ecb.ProviderConnectionString = scsb.ConnectionString;
using (SchoolDB schoolDB = new SchoolDB(ecb.ConnectionString))
Error: The entity type student is not part of the model for the current context.
You are absolutely correct. I got the solution. There is no need to keep any string in webconfig for reference to a entity model. We can use the above code for reference it. But the change is to configure the context object.
public SchoolDB(string connectionString)
: base(connectionString)
{
}
We need to change the constructor also by this format.
thanks Sampath

Different Connection Strings with Entity Framework based on Context

I have a web forms application that uses entity framework, the application is deployed on a development box, my local machine and a production box. Each of these have different connection strings.
What is the best way of handling this.
I use TFS Build Server to deploy to development and take the result of that build zip it and copy it to production manually.
I also use Web Deployment Projects if that helps
What I was doing before was when the ORM started it would choose a connection string based on the name of the root folder. With Entity Framework I don't know how to do this without having to set it on every page.
We have something vaguely similar, I created a class to wrap the EntityContext object, which sets the connection string appropriately - you'd need something similar, based on how you set your connection string:
Public Class MyEntityModel
Private _dataContext As Entities
Public Sub New()
Dim entityBuilder As New EntityConnectionStringBuilder()
entityBuilder.ProviderConnectionString = MyApplicationConnectionString
entityBuilder.Metadata = "res://*/"
entityBuilder.Provider = "System.Data.SqlClient"
_dataContext = New Entities(entityBuilder.ConnectionString)
End Sub
Public Function DataContext() As Entities
Return _dataContext
End Function
End Class
FYI You can use config transformations now in VS 2010:
http://msdn.microsoft.com/en-us/vstudio/Video/ff801895

How to use ADO.net Entity Framework with an existing SqlConnection?

I have an existing asp.net website that uses an SqlConnection.
I have added the ADO.net Entity Framework.
I have successfully connected to the database and created the .edmx file.
I am able to connect through the Entity Framework with the connectionstring that is automatically generated.
I want to use the existing SqlConnection object that I use throughout the site for the Entity Framework connection.
I do not want to have to use a second database connection for the one page that is going to use the ADO.net Entity Framework and I don’t want to change the entire site to use the new Entity Framework connection string.
Thanks for any help you can provide.
That forum post has the answer:
MetadataWorkspace workspace = new MetadataWorkspace(
new string[] { "res://*/" },
new Assembly[] { Assembly.GetExecutingAssembly() });
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
using (EntityConnection entityConnection = new EntityConnection(workspace, sqlConnection))
using (NorthwindEntities context = new NorthwindEntities(entityConnection))
{
foreach (var product in context.Products)
{
Console.WriteLine(product.ProductName);
}
}
"res://*/" is the part of your EF connection string that describes the location of your xml mapping files - in this case embedded resources in the current assembly.
You can do this by using the constructor of your generated ObjectContext that accepts an EntityConnection. When you create the EntityConnection you pass in your SqlConnection.
Andrew Peters,
Thank you for your answer.
I have been going around and around with the System.Data.EntityClient.EntityConnection.
It’s right there at my finger tips but I cannot seem to get the MetadataWorkspace parameter to work.
This is the closest example I have found (the post marked Answer):
http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/dd7b1c41-e428-4e29-ab83-448d3f529ba4/
Thanks for any help.