Specify Connection string for Entity Framework used from multiple projects - entity-framework-4

I am currently using EntityFramework 4 with POCO objects. The POCO objects are located in their own .net project (project.Models). The Context is located in the DAL project (project.DAL). I have multiple other projects that I wish to use the context/models, for Example:
project.Website
project.Webservice
project.ConsoleApplication
Question:
How do I set the Context's connection string myself?
I have noticed that the Context object automatically finds the connection string in the web.config of the website if I add it there. Do I need to do something similiar for all the other projects? This seems inelegant and i think i'd rather have a way to manually configure it from my own config file or something.
Thanks!
AFrieze

You can pass a connection string as the first argument to the ObjectContext constructor. Read it from wherever you like and pass it explicitly, if that's what you want.

Related

Stored Procedures and Entity Framework 5

I'm using Entity Framework 5, and I reverse engineer code first the database I'm using, and then I added an ADO.NET Entity Data Model so that I can use Stored Procedures as reverse engineer code first didn't provide the use of sprocs. Is this the only way to access sprocs?
Also, I realize that after the reverse engineer code first process is done a bunch of classes (tables from the database) are created but as soon as I add the ADO.NET Entity Data Model, most of the classes go away. Does anybody know why?
DbContext.Database property exposes useful methods
http://msdn.microsoft.com/en-us/library/system.data.entity.database(v=vs.103).aspx
ExecuteSqlCommand( string, object[] )
http://msdn.microsoft.com/en-us/library/system.data.entity.database.executesqlcommand(v=vs.103).aspx
SqlQuery<TEntity>( string, object[] )
http://msdn.microsoft.com/en-us/library/gg696545(v=vs.103).aspx
There is a pattern that you can follow to create or support store procedures with the code first approach. here is a link that you can use to follow this:
http://www.codeproject.com/Articles/179481/Code-First-Stored-Procedures
In few words you need to do the same that you do with model first, create a class that supports the inputs and a class that supports the result set.
And about the Data Entity Model and missing classes. You need to consider that you only can have one approach in a project: code first/(model first/database first), so this could be the reason why you are not seeing those clases.
You can use Context.Database.SqlQuery to run SP.

Error in Model classes after creating Model.Context and Model classes in ASP.Net MVC 4

I have generated xxxModel.Context and xxxModel template (in Models) from an existing database using EF 4.1 on ASP.Net MVC 4 application. After that when I build the project it gives the error for all the Model classes (POCO) saying "The type file name already contains a definition for memeber variable name". Where am I going wrong?
Thanks for help.
Clearly the file DESE.cs (and others) already contains identically named classes with properties - which are clashing with the types generated by EF. CC_Names.cs, for example, is being output by a text template - so I'm assuming you've got more than one code-generation strategy going on here from the same database.
And then you also have issues where you've re-declared the partial class CorpCostEntities again in another file with a different base to the one set by the EF code generator.
I think you might need to decide whether you want to use edmx code generation or the text-templating approach and stick to it :)

Metadata issue with multiple models & Breeze contexts

Has anyone else tried using the server-side component of Breeze.js in a solution with multiple Api Controllers for multiple EF Models?
I'm finding that after calling the MetaData endpoint on one context, all subsequent calls to MetaData endpoints in other contexts return the MetaData from the first context which was called, for example say I have two Api Controllers, each with their own MetaData endpoint:
public class CoreController : ApiController
{
readonly EFContextProvider<CoreEntities> contextProvider = new EFContextProvider<CoreEntities>();
}
public class FormsController : ApiController
{
readonly EFContextProvider<FormsEntities> contextProvider = new EFContextProvider<FormsEntities>();
}
Calling ~/Core/MetaData will return the JSON for the Core model, however a subsequent call to ~/Forms/MetaData will not return the Forms JSON, but instead the Core metadata is returned. If I call them in reverse I get the Forms metadata both times, this issue appears to persist until the host process is recycled.
I can confirm that I am able to access object data from both models as expected, so I doubt this is a routing issue.
Perhaps someone can tell me if there is some caching going on somewhere which I need to disable?
Regards,
Tom Tregenna
Ok, this should be fixed in Breeze 0.73.4, available either via nuget or zips on the breeze website.
You are right. I've tested this issue and this behaviour you reported happened. Putting breakpoints for each Metadata() method for the two Controllers, and using Fiddler, I concluded that this is not a routing issue. The two Controllers are using differents Context (contextProvider's property), but the first Metadata that was called is always returned. I guess this is Breeze's library issue. I've read the Breeze's documentation, but I have not found anything that could help.
There is another issue with the same symptoms. It is related to ambiguous references to the Entity Framework metadata in the connection string. I had two separate EDMX files, both of which were named Model.edmx (separate projects). When I referenced the assembly that contained the second EDMX file, the connection string below became ambiguous - the metadata files from both of the EDMX files fit the description.
metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;
I was able to resolve the issue by renaming one of the EDMX files.
An alternative solution would be to replace the asterisk with the full name of the assembly which contains the embedded metadata - there is actually a performance benefit to doing so. See the MSDN documentation covering Entity Framework connection strings for further details.
assemblyFullName
The full name of an assembly with the embedded resource. The name
includes the simple name, version name, supported culture, and public
key, as follows:
ResourceLib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
Resources can be embedded in any assembly that is accessible by the
application.
If you specify a wildcard (*) for assemblyFullName, the Entity
Framework runtime will search for resources in the following
locations, in this order:
The calling assembly.
The referenced assemblies.
The assemblies in the bin directory of an application.
If the files are not in one of these locations, an exception will be
thrown.
Cc716756.note(en-us,VS.100).gifNote: When you use wildcard (*), the
Entity Framework has to look through all the assemblies for resources
with the correct name. To improve performance, specify the assembly
name instead of the wildcard.

HOw can I access two database in single .edmx file?

I have created mvc3 application.
I have one .edmx already created which is based on Db1 but now
I have created a view which is based on Database2 and I need to use this view inside my project.
For that I need to update my EF .edmx file.
but when I right click and select option Update model from Database
i'm only getting all tables , view ,sps fromDb1` its obvious
But as i need to use view which is fromDatabase2how can i add it into my model.edmx` file?
please help.
If two edmx want to merge then make partial class same for both edmx file (there will be two designer classes). Add another constructor and make it parametrized, for other edmx file. Parameter to identify which edmx want to load.
Add another class file in Business layer create object of edmx partial class in this class file, Under this class when ever you want to load whom so ever edmx file pass some argument in constructor of edmx partial class constructor to identify which connection needs to open.
Pass parameter in constructor of edmx designer class, based on decided page name (custom logic or table name; That edmx will get loaded.
In web config file multiple connection strings will available for multiple edmx file.
Entity Framework does not support mapping more than one database to one model/.edmx file (see See : unify two models (edmx) with visual studio 2010)
So you'd need to create a separate .edmx file/model for the other database, and reference each model with separate contexts. You'll need 2 connection strings in your projects as well.
One "hack" might be, for i.e. MS SQL to link these two servers and expose the data from other one on first one, i.e. via view. But I think it's manageable only for few tables. With huge models this will be pain. Other databases (Firebird, Oracle, ...) support this in similar way.
What I have done , created stored procedure in db A and accessed the db B through that SP , say select * from db2.table.then create a function import for that particular SP .
This approach works well if you have both databases on same server. In case these are on different servers you can create Linked Server on B to access A using the same stored procedure approach.
Using ctx As New Entity()
ctx.Database.Connection.ConnectionString = conString
End Using

Using repository pattern in ASP.NET MVC with a SQL Server DB; how to mock repository so its unit testable without breaking OOD

I've been learning the ASP.NET MVC framework using the Apress book "Pro ASP.NET MVC Framework" by Steven Sanderson. To that end I have been trying out a few things on a project that I am not that familar with but are things that I thing I should be doing, namely:
Using repository pattern to access my database and populate my domain/business objects.
Use an interface for the repository so it can be mocked in a test project.
Use inversion of control to create my controllers
I have an MVC web app, domain library, test library.
In my database my domain items have an Id represented as an int identity column. In my domain classes the setter is internal so only the repository can set it.
So my quandries/problems are:
Effectively all classes in the domain library can set the Id property, not good for OOP as they should be read-only.
In my test library I create a fake repository. However since it's a different assembly I can't set the Id properties on classes.
What do others do when using a database data store? I imagine that many use an integer Id as unique identifier in the database and would then need to set it the object but not by anything else.
Can't you set your objects' IDs during construction and make them read-only, rather than setting IDs through a setter method?
Or do you need to set the ID at other times. If that's the case, could you explain why?
EDIT:
Would it be possible to divorce the ID and the domain object? Does anything other than the repository need to know the ID?
Remove the ID field from your domain object, and have your repository implementations track object IDs using a private Dictionary. That way anyone can create instances of your domain objects, but they can't do silly things with the IDs.
That way, the IDs of the domain objects are whatever the repository implementation decides they are - they could be ints from a database, urls, or file names.
If someone creates a new domain object outside of the repository and say, tried to save it to your repository, you can look up the ID of the object and save it as appropriate. If the ID isn't there, you can either throw an exception to say you need to create the object using a repository method, or create a new ID for it.
Is there anything that would stop you from using this pattern?
you can use the InternalsVisibleTo attribute. It will allow the types from an assembly to be visible from the tests (provided they are in different assemblies).
Otherwise you can leave the property read-only for the external objects but in the same time have a constructor which has an ID parameter and sets the ID property. Then you can call that constructor.
Hope this helps.

Resources