Problems with Entity Framework and EntitiyDataSource - entity-framework-4

I have simple scenario:
Web Project(C#) with added dll reference to below DataSource project.
Separate DataSource project (Class Library) where I added edmx file and generated POCOs with DbContext Generator.
Really, nothing special. I think every youtube instructional video I saw on Entity Framework is doing something simple.
What I discovered is that EntityDataSource simply doesn't work. I get range of error messages and I really can't see the pattern when they are showing up:
Here are some:
- Unable to load the specified metadata source
- Schema invalid and types cannot be loaded because the assembly contains EdmSchemaAttribute... loading by both name and attribute is not allowed.
Few time, don't know how, I managed to pass by this error, in that case I would get CLR error when I try to execute simple page with datasource and gridview (nothing was coded)
End to add to the problem...
I am referencing another DataSource project the same way. I am perfectly able to set this EntityDataSource without errors above. But when I click Refresh Schema, I get error "Could not find the CLR type for MyEntity.
What is wrong here.
Thanks

I was getting the EdmSchemaAttribute error message, using EF 5.0 and WCF Data Services 5.2.0. This was a data service using a DbContext-derived class, but the DbContext-derived class was in the same assembly as some EDMX files and ObjectContext-based code generated from the EDMX files.
The fix for me was to separate code-first EF code from model-first EF code (which uses ObjectContext and generates code with the [EdmSchema] attribute). By moving the code-first code into a separate assembly, the error message went away and things are working.
I hope that helps.

Related

Exception has been thrown by the target of an invocation thrown when scaffolding a controller

I created a separate Class Library project to store the Database Context and Model Classes.
In the same solution, I created an ASP.NET MVC project and referenced the Class Library project, as well as include the Connection String for the Database Context, in the project's Web.config file.
However, when I attempt to add a Controller (with views, using EF), I get the following error:
Exception has been thrown by the target of an invocation.
I am able to see the Database Context and Model Classes in the Add Controller drop down boxes, so I don't think its a referencing issue.
If anyone is also experiencing this error (with this configuration), you assistance will be greatly appreciated.
I had more than one ConnectionStrings define. I removed the default and replaced it with the ConstringStrings from my Class Library. Works fine now!
Solution taken from the following post: Application can't scaffold items
Yes, In my case, I had the Configuration block declared twice in the Web.config file. After I removed one the scaffolding worked.
I had the same problem until I fixed the version of Microsoft.EntityFrameworkCore to match Microsoft.EntityFrameworkCore.Tools. It was a version mismatch after all!

Accessing a LocalDB within an ASP.NET website from another project in solution

I have an asp.net mvc 5 website using EF, LocalDB and Code First Migrations. Requirements have now dictated that I need a need to add a console application into the mix to do some scheduled work. However this console app must call into the database functionality exposed in the web application. Also of note is that we are using LocalDB for development, but will switch to a 'proper' remote DB for production.
As such I have created a new console application within the project and added a reference to the web application so that I can call its repository functions. I know this probably isn't the best way to handle things.
For whatever reason though, when calling Save Changes on the database context from within the console application, nothing is saved to the LocalDB database. The Save function returns a number indicating that a number of rows were inserted.
I get the feeling I am making a schoolboy error somewhere. What could it be?
i`v used this in the past:
<add name="DefaultConnection"
connectionString="Server=(localdb)\v11.0;Database=WebPortalDb" providerName="System.Data.SqlClient"/>
If you want to use the functionality/database from one Project to another project then use the following::
1) Include the 'ConsoleProjectName.dll' file into your 'MVC' project's reference
2) Use that Dll into the namespace of your file.
(eg. using System.Data.Entity)
in the same way you have to use the DLL into your namespace.
3) make an object of the 'console' application's class and use the methods & other properties defined in that class.
May be this much information will be helpful for you.
This we are doing for n-tired architecture, where there are different layers (i.e. projects) in a solution to be linked with each other.

Code first database on Entity Framework 5 in another project

I've got an ASP.NET MVC 4 site with MSSQL database generated by code first approach. I want to use this database in another project. This project should crawl several tables from db, update them and send notification to users.
What is the best way to add existing database from the first project to the second project? I'm thinking about generating edmx by database, but this approach doesn't seem good enough.
You would be best moving the EF code and Entities into their own library, and then having your two different projects (Web and Windows Service) have a reference to that library.
Then, if and when your database structure or entities change, you only need to do this in one place.
If the second project is not going to modify the structure of the database, then I would use a data-first approach in your second project.
You can use codefirst mapping without problem on existing database. So simple reference assembly with datacontext in other project and it will work. (Don't forget set connection string in config file of other project)

MVC3 EF4 POCO Repository/UnitOfWork Connection Error

I implemented the T4 Repository/ Unit of Work templates by Gil Fink for use in a project I am working on, my first full scale project using MVC. I am, however, getting an error I wasn't getting before, and I can't track it down. I don't know if it's something with the templates, or just a setting somewhere I have set wrong, but I am at a lose right now. I was hoping someone would be able to shed some light on the situation.
Here's my framework setup:
MVC 3 Beta
SQL Server 2008 R2
Ninject v2.1.0.76
EF4 POCO
3 projects in the solution: Data, Entities and the MVC app.
I am doing a DB first design, and using EF to create the POCO classes, via Microsoft's ADO.NET POCO Entity Generator. I then use the T4 tool to create the repository and unit of work patterns. With that setup, and all the classes and repositories generated, I implement it into the MVC app using Ninject for DI. I am using the MVC 2 method using a Controller Factory at this point, with plans to later change it to the IDependencyResolver method.
When I use a hard-coded Mock repository, the application works as it should, however when I change it to use the IRepository binding, I get the following error:
"The supplied connection is not valid because it contains insufficient mapping or metadata information.
Parameter name: connection"
This indicates to me that the connection string for EF to connection to the DB is incorrect, however it is the default string generated by the ADO.NET Entity Data Model template. Perhaps it is also something with the .edmx settings.
Here is my connection string (using the handy Nerd Dinner database layout)
<add name="NerdDinnerEntities"
connectionString="metadata=
res://*/Model1.csdl|
res://*/Model1.ssdl|
res://*/Model1.msl;
provider=System.Data.SqlClient;
provider connection string="Data Source=Wayne;Initial Catalog=NerdDinner;Integrated Security=True;Pooling=False;MultipleActiveResultSets=True""
providerName="System.Data.EntityClient" />
Anyone with any thoughts/ hints, etc, I would be extremely appreciative.
Edit: here's the link for the T4 template I'm using:
Repository and Unit of Work T4 Template for Entity Framework
Edit2:
The error is something to do with home I'm using DI with Unit Of Work. when I remove DI, and manually have the dependencies in the controllers, it works. When I try to implement DI, it breaks.
res://*/Model1.csdl|
That * is a wildcard that says to EF "scan all the assemblies for the resource". Chances are this scan isn't finding the assembly for whatever reason.
Change * to your assembly name:
res://My.Assembly.Name/Model1.csdl|
If you are using NuGet to install your Ninject dependency, it likes to set up your DI bindings in NinjectWebCommon.cs. If loading your DI bindings requires an Entity Framework context to be instantiated, this happens too early in the application lifecycle and the application can't interpret the connection string properly.
If you think this is may be what's happening to you, see my answer here for more information.

MVC 2 and Entity Framework - Should I put Entity classed in separate layer?

I'm trying to find some information on preferred solution setup when using MVC 2 and Entity Framework, and it would seem most intuitive to me to set this web app up in 3 layers:
MyProject.Web (MVC project for presentation)
MyProject.Data (Data gateway layer using Entity Framework to speak to the DB)
MyProject.Tests (Test project as created when setting up a new MVC project)
This seems to be contrary to the examples I'm finding, and the documentation (eg, the NerdDinner example) which see the MVC project as mediating directly with the database. The NerdDinner example puts the data access in a repository class mixed in with the MVC models.
I've tried going with the way which seems best to me, and have created my "ADO.NET Entity Data Model" item in my separate Data project, but this gives me an error when I try to use MVC to list the items in it:
"Unable to load the specified metadata resource."
unless I have a copy of the Entity Data model in my MVC project as well.
Before I go too far down the road of looking into this error, I want to find out if I'm just fighting against the framework for purism when I could just be disciplined with only using data access in my repository.
so:
- Is it even possible or recommended to put my Entity Framework def in this other project?
- Will I be sacrificing certain other MVC features by separating it out in this way? (eg, validation?)
- If I'm heading in the right direction and others agree, are there any other examples or docs out there someone could point me at?
Yes, I think it's a good idea to put your entities in a separate assembly.
One way to fix the "Unable to load the specified metadata resource" error is to specify the assembly in the connection string explicitly:
<connectionStrings>
<add name="MyEntities" connectionString="metadata=res://*/AssemblyName.bin.Namespace.MyEntities.csdl|res://*/AssemblyName.bin.Namespace.MyEntities.ssdl|res://*/AssemblyName.bin.Namespace.MyEntities.msl;provider=System.Data.SqlClient;provider connection string="Data Source=SERVER_NAME;Initial Catalog=DBName;Integrated Security=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient"/>
</connectionStrings>
Note, especially, the AssemblyName.bin.Namespace.MyEntities. This is the assembly-qualified resource name (assuming the assembly is called "AssemblyName.dll". You may need to use Reflector to figure it out the first time you do this.
This answer might also be helpful.
It is certainly possible to put your Entity Framework definition in another project. Personally, I keep it in another project if the data layer will need to be shared by multiple interfaces (MVC, WCF, WPF).
Take a look at these two MSDN articles on building and using an EntityConnection.
Build an EntityConnection
Use EntityConnection with an Object Context

Resources