Attach already changed object to a data context

Problem:

Using one data context for selecting data and another for submitting the changes made. The problem is that once you  attach an object to the new context you'll lose tracking of all changes made to the object.

All changes will lost after you save change.

Solution:

Call the SetModifiedProperty method  to notify the ObjectStateManager of the data context about the changes.

Example:

AdventureWorksLTEntities context = new AdventureWorksLTEntities();
            Product product = context.ProductSet.FirstOrDefault();
            if (product != null)
            {
                product.ListPrice += 10; // product.EntityState is set to Modified
            }

            AdventureWorksLTEntities newContext = new AdventureWorksLTEntities();

            context.Detach(product); // product.EntityState is set to Detached
            newContext.Attach(product);  // product.EntityState is set to Unchanged

            ObjectStateEntry state = newContext.ObjectStateManager.GetObjectStateEntry(product);
            state.SetModifiedProperty("ListPrice"); // product.EntityState is set to Modified

            newContext.SaveChanges();



Using Database Initializers and seeding

Add the following code in global.asax.cs

protected void Application_Start()     
{
        Database.SetInitializer(new MyStoreDbInitializer());
        AreaRegistration.RegisterAllAreas();
        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);     
}

Create the following class

public class MyStoreDbInitializer : DropCreateDatabaseAlways<MyStoreDB>    
 {
         protected override void Seed(MusicStoreDB context)
         {
             context.Artists.Add(new Artist {Name = “Al Di Meola”});
             context.Genres.Add(new Genre { Name = “Jazz” });
             context.Albums.Add(new Album
                                 {
                                     Artist = new Artist { Name=”Rush” },
                                     Genre = new Genre { Name=”Rock” },
                                     Price = 9.99m,
                                     Title = “Caravan”
                                 });
             base.Seed(context);
         }
     }

How to load related object in Entity Framework

You can use the eager loading method show below to load the related objects:


public ViewResult Index()

 {

 var products = db.Products.Include(a => a.Type).Include(a => a.Supplier);

 return View(products.ToList());

 }

 

**Eager loading strategy attempts to load all data using a single query.

 

 

 

MVC3 - Using layout for views

You can specified view to use layout as following:

@{

 Layout = “~/Views/Shared/_Layout.cshtml”;

 }

 

Or you can override the _ViewStart.cshtml file within the view folder using the above.

MVC3 -Razor syntax sample

Implicit Code Expression

<span>@model.Message</span>

Explicit Code Expression


<span>ISBN@(isbn)</span>

Unencoded Code Expression

<span>@Html.Raw(model.Message)</span>

Code Block

@{

int x = 123;

string y = “because.”;

}

Combining Text and Markup

@foreach (var item in items) {

 <span>Item @item.Name.</span>

 }

Mixing Code and Plain Text

@if (showMessage) {

 <text>This is plain text</text>

 }

or

@if (showMessage) {

 @:This is plain text.

 }

Escaping the Code Delimiter

My Twitter Handle is &#64;hacked

or

My Twitter Handle is @@haacked

Server Side Comment

@*

 This is a multiline server side comment.

 @if (showMessage) {

 <h1>@ViewBag.Message</h1>

 }

 All of this is commented out.

 *@

Calling a Generic Method

@(Html.SomeMethod<AType>())

Setting variables in JavaScript using JavaScript string encode

Use the @Ajax.JavaScriptStringEncode to encode the input.

<script type=”text/javascript”>
$(function () {
var message = ‘Hello @Ajax.JavaScriptStringEncode(ViewBag.Username)’;
$(“#message”).html(message).show(‘slow’);
});
</script>

jquery dropdownlist

Get value of the selected item:

$("#ComboBox").val()

Get text of the selected item:

$("#ComboBox option:selected").text()

On select value change:

$("#ComboBox").change(function() { /* do something here */ });

Add item to the list:

$(“<option value=’new item’>new item</option>”).appendTo(“#ComboBox”);

 

SQL Server 2008: "Saving changes is not permitted"

To change the Prevent saving changes that require the table re-creationoption, follow these steps:

  1. Open SQL Server Management Studio (SSMS).
  2. On the Tools menu, click Options.
  3. In the navigation pane of the Options window, click Designers.
  4. Select or clear the Prevent saving changes that require the table re-creation check box, and then click OK.

How to set default browser in Visual Studio

As it turns out setting this is quite simple.

  1. Open a WebForm file in VS (anything ending in will do) .aspx
  2. Select the option from the menu "Browse With..."File
  3. Select your preferred browser from the list and click the "Set as Default" button

ListControl AppendDataBoundItems Property

Here is a example:

<asp:DropDownList ID="DropDownList1" AppendDataBoundItems="true" runat="server" DataSourceID="SqlDataSource1" DataTextField="country" DataValueField="country">

<asp:ListItem Text="(Select a Country)" Value="" />

</asp:DropDownList>

You can setup an initial value -- such as an initial "(Select a Country)" that are not part of the databound result. Because the "AppendDataBoundItems" property is set to true, after databinding it will then have a dropdownlist whose first value is "(Select a Country)" followed by the data you bound to the list control.