Entity Framework 7 and ASP MVC 5 - simple tasks - asp.net-mvc

I am sorry if I am asking something that has an obvious answer, but I have spent and entire day searching for resources on the subject and I fail to find or understand how to do a few basic thing with EF7.
So, here is my question.
I have an ASP MVC 5 (VNEXT) website and I am using Entity Framework 7. I have an existing database, thus I am working database-first.
So far everything was fine. I installed everything required to get my DNX EF commands up and working; I scaffolded a dbContext and I got all my tables as classes and a dbContext class.
Everything fine, all well. I was happy and continuing with my work.
However, I got to a point where I wanted to make a property of one of the generated (table) classes Required, because I use jQuery unobtrusive validation.
I have the following resource as a reference: http://ef.readthedocs.org/en/latest/modeling/required-optional.html
My first wonder is, according to this source, in the FluentAPI the property has been marked as .IsRequired(). I believe, making it required here is a whole other thing that has nothing to do with unobtrusive validation. So, the next thing explained is simply - go to your class and add the Required data annotation.
This is all fine and well, and after adding it, it works as it should.
But I immediately wondered - well, I am modifying the generated classes, am I not going to lose those changes once I update the model?
Which leads me to my final problem - I searched for a long time, I even played with the help menu of DNX EF, but I am unable to find the right way to update the dbContext and generated models after I make changes to the database.
I believed this to be something quite trivial but to my surprise I am unable to find a resource explaining how to do the update.
Can you point me in the right direction, and tell me how to update EF generated models and context after I make changes in the database schema, and what is the best way to add annotations to the properties of the generated classes?

The general consensus is that you shouldn't use your database entities as input from users directly. Instead, use ViewModels, verify those against your validation rules, then map them to database transactions.

As asp.net MVC developer I use database first and updating database is a big head ache so I use Metadata approach and create ViewModels which helps allot.

Related

Is there a simple way to add a model in ASP.NET Core MVC via the GUI, besides the package manager console?

At work, I use ASP.NET MVC (not .NET Core) with Entity Framework and SQL Server. However, I wanted to practice a bit with ASP.NET Core MVC and some other SQL Server stuff (like experimenting with SSIS) at home, so I set up a small dev environment for me to work in. I created my database and tables, populated it with information, and created the default template you get with ASP.NET Core MVC. No issues so far!
But then, when I went to add a model into my project, I had no option to add an ADO.NET Entity Data Model like I do at work. After googling around a bit, I saw a mention that you could not create these kinds of models in .NET Core applications: https://learn.microsoft.com/en-us/answers/questions/357012/can39t-find-adonet-entity-data-model-missing-visua.html. I did some more googling, and it seems like just about every single thing I'm finding online is that you have to use package manager console, and type it all out.
Is this really the only way? Surely there has to be something better... It was very nice in ASP.NET MVC when I could add the model, and then it would take me through a wizard to get everything set up. I could create a new connection string, test the connection to the database, select which tables/views I wanted to add to the model, and I was all set! It was just as nice being able to go into my model and easily update the model with new tables, columns, or anything else I needed.
I get that code-first solutions are more mainstream these days, but I want to stick with the database first approach. Is there a simple, user-friendly (non package-manager console) approach for me to add models like I used to, but still get the benefits of .NET Core? Any good tutorials out there to get me on the right track (that aren't code first)? I appreciate anyone who can point me in the right direction!

EF Code First project organization

I am having trouble getting started on my first attempt with EF and Code First mostly due to trying to find an efficent way to organize the project in Visual Studio. I wanted to try Code First so I pictured a set of class files in a separate project to describe the entites, like MyApp.Models. To build on that I imagine I need something like Fluent API to make sure the database is created the way I expect which is where I hit the first snag. I think the only way to do this is to define the context where EF generates the database. So where should that code creating the context be defined? In a separate project like MyApp.DAL? I'd also like to include Asp.Net Identity 2.0 which I believe is part of defining the context so that is included in that step. Next I assume I need to actually call the code so EF can generate the DB which requires at least a configuration setting for the connection string. Eventually I want an MVC app but maybe next is a console EXE like MyApp.ConsoleTest? Also I'd also like a Web API project which would serve the MVC app. I think those can be covered with something like MyApp.WebAPI and MyApp.ClientWebMVC. Perhaps later I could also create MyApp.ClientWPF which would leverage the work done with the Web API. Along the way I should also probably have something like MyApp.Common or Shared.Common to hold things like logging and error catching.
I think the first few steps around the entities and context are what trip me up the most. I want to try and organize the data part of the code so changes can be isolated from ruining too much in the client apps. Is there a good tutorial on project organization that addresses EF Code First that isn't overly complicated (ie Unity of Work)?

Model compatibility error

Setup
I have an app that uses ASP.NET Identity 2.0. The identity part shares a database with the rest of the tables needed by the application. So in one class library, I have a dbcontext that accesses the database for business data, and in another class library, I have the IdentityModel.cs, ie, the ApplicationDBContext.
Problem:
All worked fine, until I got in a muddle, trying to figure out how to work with migrations with the business data context. I ended up deleting the __MigrationHistory table and hence all the model metadata in the database for both the context.
I now get the following error:
Model compatibility cannot be checked because the database does not contain model metadata. Model compatibility can only be checked for databases created using Code First or Code First Migrations.
I deleted all migrations related to the business data, and re enabled migrations for that project. That had the effect of recreating the model metadata for the business dbcontext.
However, I can't figure out how to achieve the same for the Identity metadata.
Question:
How do I recreate the model metadata in __MigrationHistory for ASP.NET Identity 2.0?
Write below code in Global.asax.cs and try again...
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<TsContext>());
I had to recreate the database and start again. I am still in the dark to the extent that I don't know if Neel's answer is the correct one for a production database. Right now, I don't have the time to properly research AspNet.Identity to find the solution to the problem. Sorry.
Prevention before Cure:
What I DO know is that the problem would not happen if I hadn't deleted the __MigrationHistory table. So the issue is one of self harming and so prevention rather than curing is the best option.
Therefore, the moral of the story is:
Moral:
Never, EVER, delete the __MigrationHistory table. Learn a bit more about it BEFORE doing any thing quite so silly, feckless, carless and downright dumb.

John Pappa Partials and BreezeJS using direct support in Entity Framework for this versus doing projections in breezejs

Having run into this issue:
Collection navigation properties may NOT be set
myself for exactly the same reason
and posting this suggestion on uservoice
https://breezejs.uservoice.com/forums/173093-breeze-feature-suggestions/suggestions/3796779-repository-sample-that-serves-view-models-
After seeing the great new compact meta-data feature and reviewing the edmunds sample I am trying to put it all together and come up a solution that allows me to serve DTO's/View models versus full domain objects from a ef-codefirst web api back end and I have come up with two scenerios.
1)Use web api to return the DTO's/create the metadata in JS and use the where parameters to do filtering as required) thus as I understand it the entities can be tracked by breeze. The problem with this is that I will have to override save changes and convert dtos/viewmodels back to EF domain objects and save them. I am not certain that this is either as simple/ or as complex as I can see it being. Basically my proposed algorithm for this is to remove root objects and related children from the change set as DTOs and map them back to Domain objects which can then be added to the context and saved (seems like a lot of work and I am not totaly sure that the order this has to be done in is always knowable)
2) Follow Julie Lermans lead from the Pluralsight Enterprise EF couurse and create the partials directly in EF using code first and just let breeze work as designed. (in the course Julie creates stripped down models of Customer which have attributes placed on them that tells EF to map it to the customer table)
I would love to hear anyones thoughts on this. I am personally leaning towards #2 but I may yet be persuaded to choose #1 if there is a chance of a tool to generate the metadata from my C# clases or if the implementation of SaveChanges can be shown to be manageable and not turn into rewriting half of what EF is supposed to be doing for me)
I was looking into the same issue myself and I ended up going with option 2. For my situation, I felt that I had more control going with option 2 and that I was better able to map my data the way I wanted without feeling that I had more layers than my personal project needed. Julie Lermans "Shrink EF Models with DDD Bounded Contexts" (http://msdn.microsoft.com/en-us/magazine/jj883952.aspx) was a very helpful article for me as well.

EF4 and ASP.Net MVC to Test and Develop without mapping to an underlying database (until later)

I want to develop an ASP.Net MVC application with EF4 Model First design and only generate the actual database much later, ideally at the end of the project.
Based on some of the ideas here:
http://elegantcode.com/2009/12/15/entity-framework-ef4-generic-repository-and-unit-of-work-prototype/
I want to create something like an InMemoryObjectContext for testing and development and use IOC to switch to the SQL Server implamentation (EF generated) for UAT and production.
Is this wise?
Is it possible? If so, does anyone have any suggestions?
Does EF always need an underlying database in order to track changes, commit etc?
I've tried creating a model first but as soon as I add properties I get the following errors:
Error 2062: No mapping specified for instances of the EntitySet and AssociationSet in the EntityContainer Model1Container.
and the warning:
Running transformation: Please overwrite the replacement token '$edmxInputFile$' with the actual name of the .edmx file you would like to generate from.
The error doesn't stop the application running but worries me. I'm very very new to EF so I apologize if this is way off the mark or a dumb question. I'm hoping to get some good advice while I sit for the next few days and watch videos and read articles.
Thanks
Davy
At the very least you need mapping information "filled in". You can fill these fields with nonsense if you don't want to work against the underlying database.
If your doing Model first, right click on the designer canvas and select, "Generate Database from Model". This will automatically create convention based mappings for you without defining tables and columns. You don't even need a valid db connection to do this.

Resources