Thursday, January 19, 2012


Changing the Model in a Code-First MVC Project


  • Created a MVC 3 project
  • Used Code-First to create the db
  • Modified the model (added a column)
  • When I tried to go to the view that referenced the model I got the following error:

{"The model backing the 'TaskDBContext' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance. For example, the DropCreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data."}


  • I added the following to the Global.asax.cs file (TaskDBContext is what I setup in the model for my Task object):



References

http://weblogs.asp.net/scottgu/archive/2010/08/03/using-ef-code-first-with-an-existing-database.aspx

Add jQuery DatePicker to MVC 3


Add jQuery DatePicker to MVC 3  - 18 Jan 12

Add the DataType attribute to the date field in your model



Note:  This will also remove the time from the display.

Create the partial view Views\Shared\EditorTemplates\Date.cshtml

@model DateTime?
@Html.TextBox("", Model.HasValue ? Model.Value.ToShortDateString() : DateTime.Today.ToShortDateString(), new { @class = "date" })
<script type='text/javascript'>
    $(document).ready(function () {
        $('.date').datepicker({ dateFormat: "mm/dd/yy" });
    });
</script>

Note:  You can put this JavaScript in a separate script file and reference that in _Layout.cshtml if you would rather not have it here.

Add the necessary links to Views\Shared\_Layout.cshtml

<link href="../../Content/themes/base/jquery.ui.all.css" rel="stylesheet" type="text/css" />
<script src="../../Scripts/jquery-ui-1.8.11.min.js" type="text/javascript"></script>


References






MVC Code-First Connection String for DB


Connection string in Web.config to use to have Code-First create a db at a server:

<connectionStrings>
    <add name="TaskDBContext"
         connectionString="data source=localhost;Integrated Security=SSPI;Initial Catalog=MyProductionDB" providerName="System.Data.SqlClient"/>
  </connectionStrings>