2012 | Coding Cluster - using asp.net, c#, mvc 4, iphone, php, ios, javascript, in asp.net mvc 3 & more
 

Drop All tables in Oracle using SQL Statement

Friday

Dropping all user tables in Oracle:
                               Sometime for developer want drop all table, and this is the working example that I'm used.

Note:
  •  You need to log in to that user which you wanted to drop the tables
  •  Keep in mind, If run, it will not able to rollback

Here is the SQL Script:

BEGIN
FOR cur_rec IN (SELECT object_name, object_type
FROM user_objects
WHERE object_type IN
('TABLE',
'VIEW',
'PACKAGE',
'PROCEDURE',
'FUNCTION',
'SEQUENCE'
))
LOOP
BEGIN
IF cur_rec.object_type = 'TABLE'
THEN
EXECUTE IMMEDIATE 'DROP '
|| cur_rec.object_type
|| ' "'
|| cur_rec.object_name
|| '" CASCADE CONSTRAINTS';
ELSE
EXECUTE IMMEDIATE 'DROP '
|| cur_rec.object_type
|| ' "'
|| cur_rec.object_name
|| '"';
END IF;
EXCEPTION
WHEN OTHERS
THEN
DBMS_OUTPUT.put_line ( 'FAILED: DROP '
|| cur_rec.object_type
|| ' "'
|| cur_rec.object_name
|| '"'
);
END;
END LOOP;
END;


I got this solution from http://stackoverflow.com/questions/1690404/how-to-drop-all-user-tables

Error: 18452 Login failed for user ‘(null)’. The user is not associated with a trusted SQL Server connection.

SQL Server connection Error: 18452 Login failed for user ‘(null)’.

I had an error that I believe a lot of new user for SQL server may face during create a new Database.

             

Below is the solution that I'm used to resolve my issue

Change the Authentication Mode of the SQL server from “Windows Authentication Mode (Windows Authentication)”
to “Mixed Mode (Windows Authentication and SQL Server Authentication)”.

Run following script in SQL Analyzer to change the authentication

LOGIN sa ENABLE
GO
ALTER LOGIN sa WITH PASSWORD = ‘’
GO

OR

In Object Explorer, expand Security, expand Logins, right-click 'sa', and then click Properties. On the General page, you may have to create and confirm a password for the 'sa' login. On the Status page, in the Login section, click Enabled, and then click OK.

Select one checkbox from group of checkbox using jquery

Monday

Multiple Checkbox validation in asp.net mvc 3 using jquery:

This is the sample code for select only one check box from a check box group.


function ValidateChkBox()
    {
        var selectedCheckBoxesValue = '';

        $('#DIVID').find("input:checkbox.CheckBoxClassName:checked").each(function (i, selected) {
                                                            if (selectedCheckBoxesValue.length == 0) {
                                                                selectedCheckBoxesValue += $(selected).val();
                                                            }
                                                            else {
                                                                selectedCheckBoxesValue += ',' + $(selected).val();
                                                            }});
            // Here you also get all the comma separated values if you want else use below method for it
        if(selectedCheckBoxesValue.length == 0)
        {
            alert("Select atleast one checkbox");
        }
    }

Offline storage using Indexeddb / browsers to support IndexedDb

What is IndexedDB?
                   An IndexedDB is basically a persistent data store in the browser — a database on the client side(offline storage). Like regular relational databases, it maintains indexes over the records it stores and developers use the IndexedDB JavaScript API to locate records by key or by looking up an index.

IndexedDB API is a specification for an index database which exists in the browser. The IndexedDB is made of records holding simple values and hierarchical objects. Each of the records consists of a key path and a corresponding value which can be a simple type like string or date and more advance types like JavaScript objects and arrays. It can include indexes for faster retrieval of records and can store large amount of objects.

Which browsers (chrome/opera/firefox/IE...) to support IndexedDb?

Preliminary support for Indexed DB is included by Firefox (since version 4), Google Chrome (since version 11), and by the Internet Explorer 10 Consumer Preview and Metro style apps.
Safari, Chrome 4 and Opera support an alternate mechanism for client-side database storage called Web SQL Database.

Summary of browsers with full support.

Chrome: Version 11 onward

Opera: No current or planned support

Firefox: Version 4 onward

For good measure, IE: Version 10 onward

Compatibility table for support of IndexedDB in desktop and mobile browsers.

http://caniuse.com/indexeddb


If you new to indexedDB concept you must know about the following concepts,

WHAT IS INDEXEDDB?

WHY INDEXEDDB?

How to Opening the database in indexedDB?

INDEXEDDB - Creating an object store

ADDING DATA TO AN OBJECT STORE Adding data to an object store

QUERYING THE DATA IN A STORE.

RENDERING DATA FROM AN OBJECT STORE

DELETING DATA FROM A TABLE

for all above questions html5rocks have the solution with live demo


Fading / Blinking rounded corner button only with pure css(without image)

Wednesday

Css only Rounded corners Opacity Gradient buttons:
                                        This is the source code for, No JavaScript, No Images, No Flash - CSS Only! Blinking round corner button.

source code for css only rounded corner fade button

<html><head>
<style>
nav a#blink {
padding: 10px 10px;
margin-right: 10px;
margin-bottom: 5px;
border-radius:20px;
display: inline-block;
color: #421f00;
background-color:#e6a560;
background: -moz-linear-gradient(
top,
#e6a560 0%,
#ca6609);
background: -o-linear-gradient(
top,
#e6a560 0%,
#ca6609);
background: -webkit-gradient(
linear, left top, left bottom, 
from(#e6a560),
to(#ca6609));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#e6a560', endColorstr='#ca6609');
border-radius: 5px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border: 1px solid #ffd5ab;
-moz-box-shadow:
0px 1px 3px rgba(000,000,000,0.5),
inset 0px 0px 2px rgba(66,31,0,0.7);
-webkit-box-shadow:
0px 1px 3px rgba(000,000,000,0.5),
inset 0px 0px 2px rgba(66,31,0,0.7);
text-shadow:
0px -1px 0px rgba(171,87,13,0.4),
0px 1px 0px rgba(255,255,255,0.3); 
opacity:0.7;
-webkit-animation-name: buttonPulse;
-webkit-animation-duration: 4s;
-webkit-animation-iteration-count: infinite;
-webkit-animation-timing-function: linear;
}

@-webkit-keyframes buttonPulse { 
0% { opacity: 0.5 }

50% { opacity: 1 }

100% { opacity: 0.5 }
} 
</style>
</head>
<body>
<nav role="navigation">
<a href="http://codingcluster.blogspot.in/2012/10/fadeblinking-rounded-corner-button-only.html" id="blink">Hay Look at my skin</a>
</nav>
</body>
</html>

Demo:

MVC 3: Bind View page with more than two model classes

Friday

ASP.NET MVC 3: How to call two model class in to a single view(.cshtml)
                                             This is the sample code for load two  model class in to a single view in asp.net mvc 3. To do this you just create a composite class with both objects as its properties:

In Model
public class MoviePersonModel
{
public MvcContrib.Pagination.IPagination<MvcContrib.Samples.UI.Models.Person> Person{ get; set; }
public MvcContrib.Pagination.IPagination<MvcContrib.Samples.UI.Models.Movie> Movie{ get; set; }
}

initialize the class and apply to view.

In View
@model urNamespace.MoviePersonModel

//and access its properties: @Model.PersonModel

Please share this post with your friends. If it's useful to you. Thanks!.

ASP.NET MVC: Action Names & NonAction method (ambiguous between error the action methods)

Tuesday

MVC Case Sensitivity & Action Names & NonAction Attribute
                                                  In MVC URLs not being case sensitive. For example if you have the request “Home/About” this goes to HomeController and About action, as well as hOmE/AbOUT is going to the same controller and same action method.

Suppose if you have two about action methods in the same controller with different cases such as:

public class HomeController:Controller{
    public ViewResult About()    {
        return View();
   }
    public ViewResult aBOut()
    {
        return View();
    }
}

You will get "ambiguous between the action methods ".
when I call action method About using following url http://your applicationname/Index/ABOUT I got this server error



This means, The framework doesn't determine which "about" function to call, and throws the exception telling that the call is ambiguous. To fix this problem is to change the action name. If for some reason you don’t want to change the action name, and one of these function is not an action, then you can decorate this non action method with NonAction attribute. 

Example:

[NonAction]
public ActionResult aBOut()
{
   return View();
}
Please share this post with your friends. If it's useful to you. Thanks!.

ASP.NET MVC 4: Error during serialization or deserialization using the JSON / Changing maxJsonLength property in web.config

JSON serialization error [maxJsonLength property.]
                 In my previous project I need to retrieve ticket from Web service.When I request the web service it return a ticket as JSON format.Some time I need to retrieve more than 10 lacks ticket per requet.In that time I got the following error.

Error:
Exception information:
Exception type: InvalidOperationException
Exception message: Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.


Solution:
To solve this issue We need to set Maximum allowed length of json response in Web.config file 
The MaxJsonLength property cannot be unlimited, is an integer property that defaults to 102400 (100k).

You can set the MaxJsonLength property on your web.config like 

<configuration> 
   <system.web.extensions>
       <scripting>
           <webServices>
               <jsonSerialization maxJsonLength="50000000"/>
           </webServices>
       </scripting>
   </system.web.extensions>
</configuration> 
Please share this post with your friends. If it's useful to you. Thanks!.

How to create a hidden field in asp.net MVC 3

Sunday

ASP.NET MVC 3: hidden  field in cshtml:
                                       From your model you can creates from your modela hidden input on the form for the field  that you pass it.

It is useful for fields in your Model/ViewModel that you need to persist on the page and have passed back when another call is made but shouldn't be seen by the user.

Consider the following ViewModel class:

public class ViewModeStudent
{
    public string Value { get; set; }
    public int Id { get; set; }
}

Now you want the edit page to store the ID but have it not be seen:

<% using(Html.BeginForm() { %>
    <%= Html.HiddenFor(model.Id) %><br />
    <%= Html.TextBoxFor(model.Value) %>
<% } %>
Which results in the equivalent of the following HTML:
<form name="form1">
    <input type="hidden" name="Id">2</input>
    <input type="text" name="Value" value="Some Text" />
</form>
Please share this post with your friends. If it's useful to you. Thanks!.

A circular reference was detected while serializing an object of type 'System.Data.Entity.DynamicProxies in asp.net mvc 4

Handling Circular References ASP.NET MVC 4 Json Serialization - asp.net mvc 4
                                     In this post I will explain Circular Reference Serialization Error in MVC Entity frame work. In my latest project I need to get data from database for purpose of Autocomplete.So I need data as JSON format.

When I request the “http://localhost:xxxx/Student/GetStudentJson”

               
My http GetStudentJson Method is bellow
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.Models;

namespace MvcApplication1.Controllers
{
    public class StudentController : Controller
    {
        private SchoolDBContext db = new SchoolDBContext();

        public JsonResult GetStudentJson()
        {
      var students = db.Students .Include(s => s.Standard).Include(s => s.StudentAddress);

            return Json(students, JsonRequestBehavior.AllowGet);
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}


My mode class are following
Student.cs
using System;
using System.Collections.Generic;

namespace MvcApplication1.Models
{
    public class Student
    {
        public Student()
        {
            this.Courses = new List<Course>();
        }

        public int StudentID { get; set; }
        public string StudentName { get; set; }
        public int StandardId { get; set; }
        public virtual Standard Standard { get; set; }
        public virtual StudentAddress StudentAddress { get; set; }
        public virtual ICollection<Course> Courses { get; set; }
    }
}
Standard.cs

using System;
using System.Collections.Generic;

namespace MvcApplication1.Models
{
    public class Standard
    {
        public Standard()
        {
            this.Students = new List<Student>();
        }

        public int StandardId { get; set; }
        public string StandardName { get; set; }
        public string Description { get; set; }
        public virtual ICollection<Student> Students { get; set; }
    }
StudentAddress.cs

using System;
using System.Collections.Generic;

namespace MvcApplication1.Models
{
    public class StudentAddress
    {
        public int StudentID { get; set; }
        public string Address1 { get; set; }
        public string Address2 { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public virtual Student Student { get; set; }
    }
}
Now I will explain How to solve this problem In this error occur because the student entity class includes Standard and StudentAddress class entity. But In GetStudentJson Method tries to convert only Student class object to Json.So that I got the above error. To solve this error we rewrite the GetStudentJson method

Solution One

public JsonResult GetStudentJson()
   {
            db.Configuration.ProxyCreationEnabled = false;
            var students = db.Students;
            return Json(students, JsonRequestBehavior.AllowGet);
   }
The Out Put is Look like bellow
  [{"StudentID":1,"StudentName":"John","StandardId":1,"Standard":null,
     "StudentAddress":null,"Courses":[]}]


Solution Two
In this type we get selected error

 public JsonResult GetStudentJson()
   {
            var students = from s in db.Students select new { s.StudentID, s.StudentName,s.StandardId };

            return Json(students, JsonRequestBehavior.AllowGet);
   }
Please share this post with your friends. If it's useful to you. Thanks!.

Difference Between Viewresult() and ActionResult() / different ActionResult types - in asp.net mvc 3

Types of ASP.NET MVC 3 Action Results: 
                                         ActionResult is the general base class that all the other results are derived from like ViewResult,JsonResult and so on. ActionResult is an abstract class that can have several subtypes.
Here's a description of different ActionResult types in MVC 3


ViewResult - Renders a specifed view to the response stream

PartialViewResult - Renders a specifed partial view to the response stream

EmptyResult - An empty response is returned

RedirectResult - Performs an HTTP redirection to a specifed URL

RedirectToRouteResult - Performs an HTTP redirection to a URL that is determined by the routing engine, based on given route data

JsonResult - Serializes a given ViewData object to JSON format

JavaScriptResult - Returns a piece of JavaScript code that can be executed on the client

ContentResult - Writes content to the response stream without requiring a view

FileContentResult - Returns a fle to the client

FileStreamResult - Returns a fle to the client, which is provided by a Stream

FilePathResult - Returns a fle to the client

This way you can return multiple types of results

Please share this post with your friends. If it's useful to you. Thanks!.

ASP.NET MVC 4: create dropdownlist from an enum (Enumeration helper)

Thursday

                                                      In one of my previous article I'm explained how to create  a dropdownlist from a controller class. And in this post I'm going to explaine how to create a dropdownlist from an enum.

First create  a helper ennum class with your dropdown items. Here I'm using three options "Daily","Quickly","Weekly".

using System.Reflection;
using System.ComponentModel;
namespace EnumHtmlHelper.Helper
{
    public static class EnumDropDown
    {
        public static string GetEnumDescription<TEnum>(TEnum value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());
            DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.
                   GetCustomAttributes(typeof(DescriptionAttribute), false);
            if ((attributes != null) && (attributes.Length > 0))
                return attributes[0].Description;
            else
                return value.ToString();
        }
        public enum Interval
        {
            [Description("Daily")]
            D = 1,
            [Description("Quick")]
            Q = 2,
            [Description("Weekly")]
            W = 3
        } 
    }    
}

Then add the following code into your (Razor) view to get the dropdown list.

<div class="ddlSmall">
 @{
     var EnumInterval = from Helper.EnumDropDown.Interval n in Enum.GetValues(typeof(Helper.EnumDropDown.Interval))
     elect new SelectListItem
     {
          Value = n.ToString(),
          Text = EnumDropDown.GetEnumDescription(n),
     };
    }
</div>

The output of the above code look like this in page source

<select id="Interval" name="Interval">
         <option value="D">Daily</option>
         <option value="Q">Quick</option>
         <option value="W">Weekly</option>
</select>
The output of the above code look like this in web page


Please share this post with your friends. If it's useful to you. Thanks!.

ASP.NET - MVC 4: How to debug asp.net mvc 4 source code / application in VS 2010?

Wednesday

ASP.NET: MVC 4 Debugging applications/Projects in visual studio 2010:

Below the steps for debug your asp.net mvc 4 source code using visual studio 2010 ultimate:


  1. First close all Visual Studio instances. 
  2. Ensure that you are a member of the local debuggers group (Control Panel, Administrative Tools, Local Security Policy, Security Settings, Local Poliies, User Rights Assignment,  Debug Programs).  
  3. Change the following registry key(got start type “regedit” in “Search program and files”  and click regeedit It will open “registry edit” window) HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\10.0\Debugger\DisableAttachSecurityWarning from 0 to 1. 
  4. Go to IIS Crate a Virtual directory for your web application 
  5. Open the project in VS editor. Right click in the project and click property, it will open the property window 
  6. Click on Web,on Server tag select Use Custom web service and enter virtual path of our web application
  7. Open virtual path in Any one Browser
  8. In VS IDE click Debug tag and click Attached to process and select W3wp.exe and click attach button 
  9. Then put break point(s) and click start  with debugging. 



ASP.NET: MVC 4 Razor View Get Confirm Message Before Delete

ASP.NET MVC 4: Confirmation alert before delete:
This is the sample code for display a confirmation alert message before  delete an employe detail.
                                               
                                     
In View:

@Html.ActionLink("Delete", "DeleteEmp", new { id = item.Id }, new { onclick = " return DeleteConfirm()" })
In Script:

function DeleteConfirm(){
        if (confirm("Are you sure want to delete record"))
            return true;
        else
            return false;     
    }
In Controller:

   public ActionResult DeleteEmp(int id)
   { 
            var empDelete = (from emp in dbml.M_Employees  where emp.Id == id   select emp).Single(); 
            dbml.M_Employees.DeleteOnSubmit(empDelete); 
            dbml.SubmitChanges(); 
            return RedirectToAction("Index"); 
   }

ASP.NET MVC 4 - Solution: The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/_Layout.cshtml": "Class". or "Scripts"

Friday

ASP.Net MVC 4 Razor: Section Defined But Not Rendered Error:
                            In asp.net mvc 4 project development  you may face an error like "The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/_Layout.cshtml": "Class". and / or "The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/_Layout.cshtml": "scripts".




It means that you have no definition for  a section in your master Layout.cshtml, but you try to get that section from your View. To resolve this problem, check your view.cshtml has some thing like this

@section Class{
}


and / or

@section scripts{
}


If yes, you must define a section in your master Layout.cshtml like this
To fix this section defined but bot rendered error you just add this lines before the end of body tag in your Layout.cshtml

 @RenderSection("scripts", required: false)

 @RenderSection("Class", required: false)



Please share this post if it's useful to you. Thanks!.

iphone: Step by step guide to Publish the app to app store by iTunes Connect

Wednesday

Here is the detailed report on Publishing the iPhone application into iTunes connect.


  1. Login into https://itunesconnect.apple.com using Apple ID and Password.
  2. Click Manage Your App from iTunes Connect.
  3. Click the Add New App button to start the process of creating a new iTunes App.
  4. Here it'll ask some basic information about the application such as Company Name, App Name, SKU ID, Bundle ID.
  5. Just make sure that your Bundle ID should match with your info.plist.
  6. Finally need to upload the large size app image with 512 X 512 px. and screenshot of the application with 960 X 640 px and click the Save button.
  7. Now click the View Details button under Versions.
  8. Here click the Ready to Upload Binary button and finish the process. Now the status of the application is Waiting for Upload
  9. Now go to Xcode and choose iOS Device in the schema chooser. Then choose the "Archive" under the "Product"  menu.
  10. Now Xcode will open the Organizer window with the app in Archive tab. Here we can Validate and Distribute the app.
  11. Now the status of the app is Upload Received. After few minutes it'll change to Waiting For Review.
Please share this post if it's useful to you. Thanks!.

Source: How to create a drop down list in asp.net mvc4

Thursday

Bind data to dropdownlist in Asp.net MVC4:

           This is the basic code for creating a page with a dropdown.

The difference between clasic asp.net web forms and mvc is that mvc doesn't have those events like "selectedIndexChanged", because all the controls are pure html controls.

// in view page model


 public class DropdownViewModel
    {
        public SelectList ProductList { get; set; }
    }

// in controller action 

   public ActionResult Create()
        {
            DropdownViewModel model = new DropdownViewModel();

            List<SelectListItem> listItems = new List<SelectListItem>();
            listItems.Add(new SelectListItem()
            {
                Value = "1",
                Text = "Product 1"
            });
            listItems.Add(new SelectListItem()
            {
                Value = "2",
                Text = "Product 2"
            });
            listItems.Add(new SelectListItem()
            {
                Value = "3",
                Text = "Product 3"
            });
            listItems.Add(new SelectListItem()
            {
                Value = "4",
                Text = "Product 4"
            });
            listItems.Add(new SelectListItem()
            {
                Value = "5",
                Text = "Product 5"
            });
            model.ProductList = new SelectList(listItems, "Value", "Text");

            return View(model);
        }

//And finally this is in view page 

@model YourApplication.Models.DropdownViewModel
 @Html.DropDownList("product", Model.ProductList)

And this is the output of the above code


Avoid jQuery conflict with Other JavaScript library(prototype,YUI,mootools)

Avoid jquery conflict with other javascript libraries:
                  In this jQuery article, I will explain how to avoid jquery conflict with other javascript libraries.


javascript libraries such as YUI, prototype conflict with Jquery library as prototype library also uses `$` sign.To resolve this issue, jQuery has .noConflict() method.

.noConflict() method: Relinquish jQuery's control of the $ variable (override the $ function)
we can avoid prototype and jquery conflict using .noConflict() method.


Code:

<html>  
<title>Avoid conflict between JQuery and prototype,YUI,mootools (Other javascript Libraries)</title>
<head>  
    <script src="/js/prototype.js"></script>  
    <script src="/js/jquery.js"></script>  
<script type="text/javascript" src="../other_lib.js"></script>
<script language="javascript" type="text/javascript">  
    jQuery.noConflict();  
    jQuery(document).ready(function(){  
     jQuery("#t1").show();  
 // Do something with jQuery
   });  
     $('t1').show();  
  // Do something with prototype
 </script>  
 </head>  
 </html> 

.NET Framework: Csharp(C#) Equivalents of SQL Server 2005 DataTypes

Tuesday

SQL Server Data Types and Their .NET Framework (c#) Equivalents:
                    The following table lists Microsoft SQL Server data types, their equivalents in the common language runtime (CLR) for SQL Server in the System.Data.SqlTypes namespace, and their native CLR equivalents in the Microsoft .NET Framework.




SQL Server data type CLR data type (SQL Server) CLR data type (.NET Framework)
varbinary SqlBytes, SqlBinary Byte[]
binary SqlBytes, SqlBinary Byte[]
varbinary(1), binary(1) SqlBytes, SqlBinary byte, Byte[]
image NoneNone
varchar NoneNone
char NoneNone
nvarchar(1), nchar(1) SqlChars, SqlString Char, String, Char[]
nvarchar SqlChars, SqlString
SQLChars is a better match for
data transfer and access,
and SQLString is a better match for
performing String operations.
String, Char[]
nchar SqlChars, SqlString String, Char[]
text NoneNone
ntext NoneNone
uniqueidentifier SqlGuid Guid
rowversion NoneByte[]
bit SqlBoolean Boolean
tinyint SqlByte Byte
smallint SqlInt16 Int16
int SqlInt32 Int32
bigint SqlInt64 Int64
smallmoney SqlMoney Decimal
money SqlMoney Decimal
numeric SqlDecimal Decimal
decimal SqlDecimal Decimal
real SqlSingle Single
float SqlDouble Double
smalldatetime SqlDateTime DateTime
datetime SqlDateTime DateTime
sql_variant NoneObject
User-defined type(UDT) NoneSame class that is bound to the
user-defined type in the same assembly
or a dependent assembly.
table NoneNone
cursor NoneNone
timestamp NoneNone
xml SqlXml None
For more details please review this link http://msdn.microsoft.com/fr-fr/library/ms131092(v=sql.90).aspx




Create a Foreign Key relationship using Code First Entity Framework and asp.net MVC4

Saturday

Entity Framework Code First: Add a Foreign Key relationship in asp.net MVC 4:

When building an single page application in MVC4 using Entity Framework Code First you might run into the following exception:

Unable to retrieve association information for association 'Models.Product_Parent'. Only models that include foreign key information are supported. See Entity Framework documentation for details on creating models that include foreign key information.

This is due to the way you've defined the relation ships in the dbContext. Lets say me have a dbContextcontaining products which can have child products, you would write the following code:

public class Product
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual Product Parent { get; set; }
}
public class ProductContext : DbContext
{
    public DbSet<product> Products { get; set; }
}


This should be enough to let EF know there is a relationship in there, but sadly it's not. We can solving this by following way:

we can create an extra property ParentId give this a ForeighKeyAttribute that links it to the Parent property.

[ForeignKey("Parent")]
public int? ParentId { get; set; }
public virtual Product Parent { get; set; }


 
 
 

RECENT POSTS

Boost

 
Blogger Widgets