So I've found similar questions, but could really use some help! I have an Entity Framework Application with a whole bunch of tables. I've had to add a new table, and I understand that I can get the model to update using the wizard from .edmx file. The problem is that I REALLY don't want to udpate all of the other models. I've added validation for my models as they're being used in forms, regenerating these models will get rid of all that code. Any suggestions? Thanks a lot.
You won't be able to preserve the changes you made to the auto-generated classes as part of the .edmx.
This may not be the answer you want to hear, but your situation is one of many reasons to use different classes for your user submitted data (i.e. web form in your case).
A few other reasons you should separate your models:
Prevent over-posting which could result in bad data or even security issues
Keep your data models clean and simple by avoiding having UI specific properties (e.g. SelectList which is an object to help populate <select> elements, but doesn't need to be part of the database)
Related
I'm not an ASP.NET programmer, but, as it happens in life, I had to do some minor projects using it. Now came another one in which I have to implement some custom solutions and I haven't figured it out yet - I need some tip or maybe a piece of advice like "don't go that way" ;)
Previously it was simple - there was a table in DB, there was an adequate model and a view that worked with it - worked like charm. Now it's a little bit more complicated.
The "site" is going to contain, shortly and generally speaking, a survey - but a fully configurable one, unfortunately. In another product there's gonna be a configuration manager that will allow user to define pages, block types, questions, steps and so on and will generate an XML.
For the time being, in accordance with the specification, in the site's database I'm going to have only one table which will contain just a key and the XML generated by the configurator (and maybe some additional, not important information). Now - I need to parse this XML and build the site containing pages and other elements corresponding to it.
And that WOULD not be a problem, but I don't really know how to work that way using asp.net + mvc and can't find any piece of advice that would help me anyhow. Should I create an object that would somehow fake being a model and allow me to work for example on a dataset generated from XML? Or just create a model of the mentioned table and work with the XML directly on the view (I don't like even such an idea itself)? Or - having to do something like that - just give up on MVC and use only "clear" ASP.NET? Or maybe something else?
I'll be very grateful for any help.
And I hope I described what I need understandably ;)
If the XML documents have a schema defined then you can easily generate a class that matches the document using the xsd.exe tool. The document can then be deserialized into an instance of that class using existing functionality in the .Net framework. Just google .Net Xml serialization :-)
Now, if you don't have a schema you could create one if you are sure that you know the format of the Xml. Alternatively you could create a class that matches the format you expect to get and then parse the Xml manually. This last option is much more work, so I wouldn't recommend it.
In any case, the class you end up with should contain all the data you need from the Xml document and can then be used as the Model in your MVC page. As long as you can use the standard Xml deserialization technique then this should be quite easy and painless.
Can anyone tell how to update table rows dynamically in entity framework? I am new in entity framework. Thanks in advance.
This is a pretty general question, but what you need to do is basically this:
Access your data context.
Get a given object (/record) from your context (/database).
Change the object.
Call SaveChanges() on the data context.
If you are learning EF a site that helped me a lot when I was learning it is http://msdn.microsoft.com/en-us/library/gg696194(VS.103).aspx. It contains lots of information in problem/solution format. You can also look at this book:
http://www.amazon.com/Programming-Entity-Framework-Building-Centric/dp/0596807260/ref=sr_1_1?ie=UTF8&qid=1355991856&sr=8-1&keywords=entity+framework
or this book:
http://www.amazon.com/Programming-Entity-Framework-Code-First/dp/1449312942/ref=sr_1_4?ie=UTF8&qid=1355991858&sr=8-4&keywords=entity+framework
which are both quite useful depending on whether you wish to use the designer or Code First.
Most MVC tutorials I've been reading seem to create 4 View objects for each Model. For example, if my Model is "Foo", there seem to be 4 .cshtml files: Foo/Create, Foo/Delete, Foo/Details, and Foo/Edit. Using the VisualStudio "scaffolding" helper does this as well.
Is this really considered MVC best-practice? It just feels wrong to have 4 classes that are 80-90% identical to each other. When I add a new field to Foo, I need to edit all 4 .cshtml files. This sort of dual-maintenance (quad-maintenance?) just makes my OO skin crawl.
Please tell me: is there an expected/accepted best-practice which handles this differently? Or, if this really IS accepted best-practice, tell me why the quad-maintance shouldn't make me squirm.
I'm a reasonably skilled veteran of ASP.NET / c# / OO Design, but pretty new to MVC; so apologies if this is a noob question. Thanks in advance for your help!
Edit: thanks for all the replies! I marked the most thorough one as the answer, but upvoted all that were helpful.
You'll probably need between two and four different views:
List (for viewing many things)
View (for viewing a single thing. Might not be necessary, if it's OK to use Edit as View, or if List has room to show all properties)
Create
Edit (can be the same as create, if you code cleverly)
Thus, if your model doesn't have too many properties to show them all in a table, and if you're OK with not having a static, non-editable view for just examining, you can get well away with just List and Edit, and scrap the other two.
However, this doesn't solve your problem of double (or triple) maintenance if you update your model. There's other magic for that ;)
In ASP.NET MVC 3, there are extensions on HtmlHelper that let you do Html.DisplayForModel() and Html.EditorForModel(). These use predefined templates to nest themselves into your object and draw up display/edit fields for all public properites. If you pass DisplayForModel an IEnumerable<Foo>, it will create a table with column headers that are the property names of Foo (using the DisplayName attribute information if you supplied it) and where each row represent one Foo instance. If you give EditorForModel a Foo, it will create a <label> and an <input> for each public property on Foo.
All of the templates used by these powerful extension methods can be replaced by you, if you're not happy with the defaults. This can be done either on the level of Foo, in which case you'd be back in your double-maintenance scenario, or on lower levels (such as string or DateTime) to affect all editor/display fields generated with the templates.
For more information on exactly how this works, google "ASP.NET MVC 3 editor templates" and read a couple of tutorials. They'll explain the details much better than I could.
The views that ASP.NET MVC create for you don't necessarily need to be the views that you use in production. I found those just to be handy while developing quick prototypes or to test the database CRUD operations. Feel free to create whatever view(s) you would like to handle the operations.
I would generally just have 1 or 2 views to handle the basic operations and not use the built in views that are generated. For example, 1 view for adding, editing, or details and 1 view to show a list of objects.
It all depends on your application.
If you have a single item, you don't need a List view. If you can't edit it, then you don't need an edit view. Create and Edit can often be the same view, unless there are special things you need to do in one, but not the other.
In other words, use as many views as you need. There's no hard and fast rule here. The scaffolding is just there to help you on your way. Many kinds of apps will work just fine using the scaffolding, and won't require advanced HTML or Javascript.
Why would you want multiple views? Well, let's take the display and edit functions. You could create one view, in which you use if statements to determine the edit mode of the view, however this will complicated the view logic and views should be as simple as possible.
The reason to create seperate views is that its easier to maintain than one gigantic view with tons of conditional logic in it.
You can use exactly the same view when you are performing [HttpGet]. Given that you pass a proper ViewModel to this view, it will populate with appropriate data every time whether you are loading create, update, or delete Action.
The problem becomes apparent when you try to post that data to a specific Action.
Naturally View should have only one form, which will be used for posting data. When you declare this form, you specify which exactly Action to use for Post.
Having 3 different Submit buttons in that form will not make a difference since all of them will post the same form to the same Action.
You could do some javascript tweaking on OnClick event for these buttons to change Action to which data is posted, but this definitively would not be best practice.
Buttom line: having 4 different views for each of the CRUD actions is the best practice for MVC.
I tend to create the following for an object's CRUD ops:
index
_form (partial)
new
update
delete
view
As the same form is shared between new and update, there is very little difference between the two. It really depends on how much you want the variation to be, honestly.
As for delete, this is optional. I like to have a view in case javascript is disabled.
edit:
You mention view models and the guy above posted a long, convoluted (no offense) VM code sample.
Personally, I hate classes written to basically mirror domain objects and are only used to "move" data. I hate VMs. I hate DTOs. I hate everything that makes me have to write more code than is necessary.
I guess I've drank the coolaid of other frameworks (rails, sinatra, node.js) to the point where I can't stomach the idea of tossing DRY to the wind.
I personally say skip um.
Edit2 I forgot list..
I have a database I'd like to create an entity from, and then generate RESTful output.
My objective is to add a property to one of the tables once it becomes an entity. The data for that property would be one I'd come up with through calculations done on a few different fields in the table. From there, the code generator would create RESTful output like it normally does.
I have managed to be able to update the SSDL, CSDL, and the mapping sections of the edmx file along with using the SampleEdmxCodeGenerator as a custom tool. When I have all the sections in the edmx file filled out with my custom property, the svc fails because (I'm assuming) the property doesn't exist in the database. If I leave the property out of the SSDL, but put it in the client schema (CSDL) and the mapping section, I can't build my project.
I've modified the partial class and added to it, but the problem there is that I need to populate the methods on the creation time of the class, and I haven't been able to do that yet.
Am I headed in the right direction, or is this not possible? It seems like I should be able to do this with minimal effort, but I keep hitting walls.
I think you're taking detours to get where you want. I haven't used either of these approaches (recently), so they might not do exactly what you're after, but you could try this:
Create a partial class file right next to the .edmx model, which has the same name as your entity.
In it, specify the property you want as a read-only property, that does the calculations on each get.
Partial Classes and Partial methods were the first part of my answer. What I'm essentially trying to do I can't do. I can manipulate data that is returned by using partial methods and partial classes. I can plug the OnmethodnameChanged() method to format the data how I'd like it to be shown, but that only gets me part way to my desired result.
What I would also like to do, is create a property c, which doesn't exist as a column in the database (and therefore does not exist in my entity), calculated from a couple different properties in the database (say a and b), and then add property c to the entity framework class. In doing this, I figured it would then get generated into the RESTful webservice output.
A problem that occurs comes from the need for the class to update any changes you make, and have it propagate back to the data source. I didn't care about that, because I want my property to be read only. From what I've gathered this isn't possible.
For reference, these two posts really helped:
Adding custom property to Entity Framework class
(I can only post one url currently, so here is the address to the other article)
social.msdn.microsoft.com/Forums/en-US/adodotnetdataservices/thread/b7a9e01d-c5c2-4478-8f01-00f7f6e0f75f
What I've decided to do, is to expose my entity as I've done so far, then consume the RESTful service that manipulates data and reformats it, and introduces needed properties. I'll turn the results into my own data object, and use that as a datasource to be exposed by yet another RESTful web service. I think this website gives a good example on how to expose a custom datasource.
mstecharchitect.blogspot.com/2008/12/surfacing-custom-data-source-in-adonet.html
If for some reason that is too slow, I suppose I could just make another table in my database that has a reworking of the data, and the calculated output in a format I'm looking for. The thing I want to avoid is having my resulting client having to do any of the data manipulation since it will be on some micro devices like palms, iphones, and blackberries.
Hope that helps anyone else with the same problem. It seems that is a shortfall in the current version of Data Services, but to some extent, I'm sure they'll be addressing it in later versions. Maybe T4 and .net 4.0 will be addressing it. I'm not sure.
By picking MVC for developing our new site, I find myself in the midst of "best practices" being developed around me in apparent real time. Two weeks ago, NerdDinner was my guide but with the development of MVC 2, even it seems outdated. It's an thrilling experience and I feel privileged to be in close contact with intelligent programmers daily.
Right now I've stumbled upon an issue I can't seem to get a straight answer on - from all the blogs anyway - and I'd like to get some insight from the community. It's about Editing (read: Edit action). The bulk of material out there, tutorials and blogs, deal with creating and view the model. So while this question may not spell out a question, I hope to get some discussion going, contributing to my decision about the path of development I'm to take.
My model represents a user with several fields like name, address and email. All the names, in fact, on field each for first name, last name and middle name. The Details view displays all these fields but you can change only one set of fields at a time, for instance, your names. The user expands a form while the other fields are still visible above and below. So the form that is posted back contains a subset of the fields representing the model.
While this is appealing to us and our layout concerns, for various reasons, it is to be shunned by serious MVC-developers. I've been reading about some patterns and best practices and it seems that this is not in key with the paradigm of viewmodel == view. Or have I got it wrong?
Anyway, NerdDinner dictates using FormCollection och UpdateModel. All the null fields are happily ignored. Since then, the MVC-community has abandoned this approach to such a degree that a bug in MVC 2 was not discovered. UpdateModel does not work without a complete model in your formcollection.
The view model pattern receiving most praise seems to be Dedicated view model that contains a custom view model entity and is the only one that my design issue could be made compatible with. It entails a tedious amount of mapping, albeit lightened by the use of AutoMapper and the ideas of Jimmy Bogard, that may or may not be worthwhile. He also proposes a 1:1 relationship between view and view model.
In keeping with these design paradigms, I am to create a view and associated view for each of my expanding sets of fields. The view models would each be nearly identical, differing only in the fields which are read-only, the views also containing much repeated markup. This seems absurd to me. In future I may want to be able to display two, more or all sets of fields open simultaneously.
I will most attentively read the discussion I hope to spark. Many thanks in advance.
I am doing it like this (the mapping is done automatically inside modelBuilder with the ValueInjecter):
I have a sample asp.net-mvc application where I demonstrate the best practices of doing this in mvc, you can see it in the download of the valueinjecter
public ActionResult Edit(long id)
{
return View(modelBuilder.BuildModel(personService.Get(id)));
}
[HttpPost]
public ActionResult Edit(PersonViewModel model)
{
if (!ModelState.IsValid)
return View(modelBuilder.RebuildModel(model));
personService.Save(modelBuilder.BuildEntity(model));
return RedirectToAction("Index");
}
a quick demo of the ValueInjecter:
//build viewmodel
personViewModel.InjectFrom(person)
.InjectFrom<CountryToLookup>(person);
//build entity
person.InjectFrom(personViewModel)
.InjectFrom<LookupToCountry>(personViewModel);
There have been a few posts recently around the issue of validating your models, resulting in this post from Brad Wilson "Input Validation vs. Model Validation in ASP.NET MVC".
The initial issue was to do with how ASP.NET MVC handled validating a posted model, and if there were elements of your model that you didn't want edited and didn't supply fields for in the view, but your controllers were working with the whole model, it's possible that someone could craft a POST to your controller with the additional fields.
Therefore using a View specific Model enables you to ensure that only the fields you want edited can be edited.
I have the exact same problem, but I wouldn't be able to formulate it that well.
In my case, there would be tons of ViewModels, because different users would see different forms based on a set of roles. I think the 1:1 relation between ViewModel and View is very vague. What if I write an uber-View which pretty much simply uses EditorForModel and not much more? Now I have one, albeit highly degenerate, view for everything, so I also have only one ViewModel?
My idea was to write an EditorForModel that works not only based on reflection (that is, information known at compile time), but also on (domain specific) runtime rules, for example governed by the current user's role, the current time, etc. Consequently, one also needs to write a custom ModelBinder with validation as well as a custom mapping from Model to ViewModel. Still, this keeps me from writing stupid and thus error-prone code.
Since my Model (or DomainModel) contains a lot of logic, I don't want it to be modified via ModelBinding at all. Moreover, since it is impossible to know what fields will be present at compile time, providing an appropriate ViewModel is impossible. However, the 'full', i.e. maximal ViewModel is known. Mapping from the ViewModel to the Model again involves custom code, but as long as the rules can be formalized, that should work out.
Sorry my text is very confusing, but I am very confused right now myself, plus I gotta run. Like C.T., couldn't comment either.
Check this out. This is the way to go with ASP.NET MVC 2.
public void Update(MyModel model)
{
var myModelObject = MyRepository.GetInstance(model.Id);
if(myModelObject != null)
{
ModelCopier.CopyModel(model, myModelObject);
}
MyRepository.Save(myModelObject);
}
ModelCopier.CopyModel(obj from, obj to) is a new function in the latest MvcFutures. Also be sure to check out the Extensible Model Binder in MVC Futures 2.