Microsoft Developer Network > Samples >
ASP.NET MVC Application Using Entity Framework Code First

ASP.NET MVC Application Using Entity Framework Code First

A Visual Studio project which shows how to use the Entity Framework in an ASP.NET MVC web application project, using the Code First development approach.


Select a language
 
 
 
 
 
(51)
35,710 times
1/18/2012
E-mail Twitter del.icio.us Digg Facebook
Add To Favorites
Description
Browse Code
Q and A (12)
VB.NET
C#
Sign in to Ask a Question


  • Hi,Could you tell me that where does the code set the Primary key for table Department?
    3 Posts | Last Post January 06, 2012
    • Could you tell me that where does the code set the Primary key for table Department?
      
      The class did not have a attribute for the property DepartmentID.
      ------------
      public class Department
          {
              public int DepartmentID { get; set; }
      
              [Required(ErrorMessage = "Department name is required.")]
              [MaxLength(50)]
              public string Name { get; set; }
      
              [DisplayFormat(DataFormatString = "{0:c}")]
              [Required(ErrorMessage = "Budget is required.")]
              [Column(TypeName = "money")]
              public decimal? Budget { get; set; }
      
              [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
              [Required(ErrorMessage = "Start date is required.")]
              public DateTime StartDate { get; set; }
      
              [Display(Name = "Administrator")]
              public int? PersonID { get; set; }
              
              [Timestamp]
              public Byte[] Timestamp { get; set; }
      
              public virtual Instructor Administrator { get; set; }
              public virtual ICollection<Course> Courses { get; set; }
          }
      ---------------------
      
    • This is explained in the first tutorial (http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application):  it's an EF Code First convention that the a property named classname + ID or just ID is interpreted as the primary key.
    • Thank you,Tom Dykstra!
      
      I am sorry about that i did not read the whole Tutorials.
  • filtering using more than one attribute
    5 Posts | Last Post January 06, 2012
    • i have requirerment like:
      filter using two columns with "OR" condion
      for example: Student Number,department Name
      records for specified department including the record for that student  number specified if department is different needs to be displayed....
      for this how can i customize lamda expression in my generic repository...
    • For questions that aren't about actual code in the project or the tutorials, the best place to get specific answers would be the ASP.NET EF forum (http://forums.asp.net/1227.aspx) or StackOverflow.com.
    • In this proj.. we have get method with three arguments in GenericRepository, similar way i need one method
      
      i was not familier with lamda expressions thats why...i am facing the problem...
      
    • For an excellent introduction to lambda expressions, see this book chapter that is posted in several places on the internet:  http://www.informit.com/articles/article.aspx?p=1570280
      
    • Tom, Thank You very much...
      i have basic idea for EF code First Approch but i want strong knowledge on that, please help me out.. 
  • Context in same namespace as entities
    3 Posts | Last Post January 02, 2012
    • Hi Tom, I was reading your tutorial and I read this comment "(This class is in the Models namespace, because in some situations Code First assumes that the entity classes and the context class are in the same namespace.)" and I was wondering if you could tell in which situations this is needed or maybe point me to some article or doc where this is explained in more detail?
      
      Thanks for your input on this! Nice tut BTW!!!
    • Hi Aloaiza, This issue was reported as a bug to the Entity Framework team, but was not reported as an issue by enough customers for them to prioritize it high enough to investigate further, and so its precise causes remain unknown.  It seems to be a combination of factors within EF and outside of EF, because you can load the exact same project on two different machines, and in one you don't have the namespace confusion bug and on the other you get it. When I created the tutorial everything worked fine, then some of the first customers to use the tutorial reported a problem, and so I tried it on several different machines, and on some machines I got the same error they did.  I found this way of ensuring that the error did not occur on any of the machines and changed the tutorial to reflect that workaround.  There is a known bug in EF that makes it impossible to have the same class in different namespaces in the same assembly, but this does not seem to be related to that bug.
      Tom
    • Hummm...I see, thanks for taking your time to answer this!
  • Can Not .Include(i => i.OfficeAssignment)?
    4 Posts | Last Post December 22, 2011
    • I change the code to
      
      viewModel.Instructors = db.Instructors
                      .Include(i => i.OfficeAssignment)
                      .Include(i => i.Courses.Select(c => c.Department))
                      .OrderBy(i => i.LastName);
      
      and got the error
      
      
      Server Error in '/' Application.
      --------------------------------------------------------------------------------
      
      The ResultType of the specified expression is not compatible with the required type. The expression ResultType is 'Transient.reference[ContosoUniversity.Models.Person]' but the required type is 'Transient.reference[ContosoUniversity.Models.Instructor]'. 
      Parameter name: arguments[0] 
      Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 
      
      Exception Details: System.ArgumentException: The ResultType of the specified expression is not compatible with the required type. The expression ResultType is 'Transient.reference[ContosoUniversity.Models.Person]' but the required type is 'Transient.reference[ContosoUniversity.Models.Instructor]'. 
      Parameter name: arguments[0]
      
      Source Error: 
      
      
      Line 19:         <th>Courses</th>
      Line 20:     </tr> 
      Line 21:     @foreach (var item in Model.Instructors) 
      Line 22:     { 
      Line 23:         string selectedRow = ""; 
       
      
      Source File: h:\sharefolder\yangyi\PublishTemp\Views\Instructor\Index.cshtml    Line: 21 
      
      Stack Trace: 
      
      
      [ArgumentException: The ResultType of the specified expression is not compatible with the required type. The expression ResultType is 'Transient.reference[ContosoUniversity.Models.Person]' but the required type is 'Transient.reference[ContosoUniversity.Models.Instructor]'. 
      Parameter name: arguments[0]]
         
    • My ConnectString is 
      
      <add name="SchoolContext" providerName="System.Data.SqlClient" connectionString="Server=.;Database=School;User id=sa;Password=sa;"/>
      
      Is there something wrong?
    • This tutorial:  
      http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-inheritance-with-the-entity-framework-in-an-asp-net-mvc-application
      explains that this does not work due to a bug in the current version of EF:
      
      The current version of the Entity Framework doesn't support eager loading for one-to-zero-or-one relationships when the navigation property is on the derived class of a TPH inheritance structure. This is the case with the OfficeAssignment property on the Instructor entity.
    • Thank you! Tom Dykstra.
  • Including business logic in EF entities
    2 Posts | Last Post December 02, 2011
    • This application is really great and it is a complete package that helps in learning EF and MVC quickly without having to read hundreds of pages of a book (and get lost in the middle) just to get started. I may still have to read the book if I need to go into details, but this tutorial is very good for a beginner and I like the way the concepts are explained with examples and code snippets. however it would have been more helpful if this application had some amount of business logic in it as well to make it more close to a real world application. I think EF 4.1 allows us to implement business logic using partial classes (though its main purpose is data management), I would like to see it in action if possible. it will be useful if it demonstrates how to implement business logic (not just a simple validation using annotations) within an entity and across multiple entities. Thanks in advance.
    • Thank you for the suggestion - I'll add that to the list of things we should consider for the next release of the tutorials that this project accompanies.  We don't have a projected release date for that update yet.
  • How to use this Application with Full SQL server?
    2 Posts | Last Post September 06, 2011
    • How to use this Application with Full SQL server? and what's code-first connection string database-first connection string ? this question make me crazy , can you help me ?  
      
      And i just want to know , When this application with full sqlserver  , can i need not create database and table ? just like Sqlserver Compare ?
      
      please e-mail to me : Michaelman@live.cn i'm michael , thanks.
    • For an example of a connection string for full SQL Server, see Connection Strings under Deployment Considerations in this article in MSDN Magazine:  http://msdn.microsoft.com/en-us/magazine/hh126815.aspx
      The same deployment section of the article explains how to set up Code First so that it doesn't create database and tables.
  • I use my new vs 2010 prof, when openening the sln file, I get this message?
    2 Posts | Last Post July 11, 2011
    • C:\Users\raoul\Documents\Visual Studio 2010\Projects\ContosoUniversity\ContosoUniversity\ContosoUniversity.vbproj : error  : The project file 'C:\Users\raoul\Documents\Visual Studio 2010\Projects\ContosoUniversity\ContosoUniversity\ContosoUniversity.vbproj' cannot be opened.
      
      The project type is not supported by this installation.
    • Make sure you have installed the prerequisites which are listed at the top of the tutorial pages -- http://www.asp.net/entity-framework/tutorials/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application
      
  • The type or namespace name 'Compare' could not be found
    2 Posts | Last Post May 02, 2011
    • Weird. I downloaded the solution and get the errors below when I compile. Looking around the web, it appears I'm the only person who has ever encountered this problem. Running Win7 Home Premium, VS2010 Ultimate with SP1. Any ideas?
      
      Thanks, Hoytster
      
      Error	3	The type or namespace name 'Compare' could not be found (are you missing a using directive or an assembly reference?)	C:\Data\MVC\ContosoUniversity\ContosoUniversity\ContosoUniversity\Models\AccountModels.cs	26	10	ContosoUniversity
      Error	5	The type or namespace name 'Compare' could not be found (are you missing a using directive or an assembly reference?)	C:\Data\MVC\ContosoUniversity\ContosoUniversity\ContosoUniversity\Models\AccountModels.cs	64	10	ContosoUniversity
      Error	2	The type or namespace name 'CompareAttribute' could not be found (are you missing a using directive or an assembly reference?)	C:\Data\MVC\ContosoUniversity\ContosoUniversity\ContosoUniversity\Models\AccountModels.cs	26	10	ContosoUniversity
      Error	4	The type or namespace name 'CompareAttribute' could not be found (are you missing a using directive or an assembly reference?)	C:\Data\MVC\ContosoUniversity\ContosoUniversity\ContosoUniversity\Models\AccountModels.cs	64	10	ContosoUniversity
      
    • Even if you already have SP1 there are several other prerequisites that need to be installed, such as Entity Framework 4.1, MVC 3 Tools Update, and SQL Compact Tools for Visual Studio.  You can get all of them by clicking on the link to install SP1 at the top of the first tutorial -- Web Platform Installer will figure out what is missing and install what you need.
  • VS 2008 support
    2 Posts | Last Post May 01, 2011
    • Can I use this application with
      * Visual Studio 2008
      * SQL Server 2008 Enterprise Edition
    • You can use it with SQL Server 2008 with a different connection string, but it requires Visual Studio 2010 and ASP.NET 4.
  • How to use this Application with SQL server?
    9 Posts | Last Post April 29, 2011
    • How to use this Application with SQL server?
       Thanks!
    • The application is set up to use SQL Server Compact; if you want to use SQL Server Express instead, all you have to do is remove the SchoolContext connection string from the Web.config file and a SQL Server Express database will be created automatically. If you want to use full SQL Server you will need to change the SchoolContext connection string to point to the SQL Server instance you want to use.
    • If you want to use full SQL Server ,but I don't know how to change  the SchoolContext connection string .
      Link this?
      <add name="SchoolContext" connectionString="metadata=res://*/DAL.SchoolModel.csdl|res://*/DAL.SchoolModel.ssdl|res://*/DAL.SchoolModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=.\;Initial Catalog=School;user id=sa;Password=123;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" />
    • I don't know metadata how to work?
      
      Thanks!
      Can
    • Your example look like a Database First connection string. You should be able to use a normal SQL Server connection string (i.e., without .csdl/.ssdl/.msl etc.) with Code First.  For more information on connection strings see this site:
      http://www.connectionstrings.com/
      
    • I chang the SchoolContext connection string like this:
            <add name="SchoolContext" 
                 connectionString="data source=.\;Initial Catalog=School;user id=sa;Password=35683568;" 
                 providerName="System.Data.SqlClient" />
      But Error Like this:
      Model compatibility cannot be checked because the database does not contain model metadata. Ensure that IncludeMetadataConvention has been added to the DbModelBuilder conventions. 
      
    •  The database School is worked well,but I just don't know how to change the connection string.
    • See this forum thread which is about the same error message:  http://forums.asp.net/p/1673379/4385705.aspx
      If the cause in your case is different, I'm not familiar with it and I would recommend posing a question on StackOverflow or the ASP.NET forum.
    • Happy to see that!
      
      And Thank you for sharing your solution to us! That must be very useful!
      
      
1 - 10 of 12 Items   
« First   < Prev   1  2    Next >   Last »