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.

 
 
 
 
 
(69)
153,211 times
Add To Favorites
11/5/2012
E-mail Twitter del.icio.us Digg Facebook
Sign in to Ask a Question


  • checkbox does not retain his state
    4 Posts | Last Post August 31, 2012
    • Hello, i followed this example to Create an application, so i have in my DB, a table account and a table role and the relation ship between account and role is many to many, so i have a association table account_role, i work with EF database first and i generate my POCO with EF DbContext Generator, i want an edit Account page dispay a checkbox ,My Problem is the checkbox does not retain its state and also each time when I click the save button it removes the added roles (choose)
             
    • Since this is not a question that is about the sample code or the tutorial, please post your question along with samples of your code to the ASP.NET forum:  http://forums.asp.net/1227.aspx/1?ADO+NET+Entity+Framework+LINQ+to+SQL+NHibernate
    • Thank you Tom Dykstra for your answer, i posted My thread in http://forums.asp.net/t/1785185.aspx/1?Asp+MVC3+checkbox+does+not+retain+its+state
      But i don't find  a valid answer 
      thank you to help me 
    • Thanks. This was useful. As I was stuck up at this point.
  • Operation could destabilize the runtime.
    2 Posts | Last Post August 29, 2012
    • I get an "Operation could destabilize the runtime" exception when running the code on my computer with both VS2010 and VS2012. On another computer with only VS2010 I have no issues.
      
      Server Error in '/' Application.
      --------------------------------------------------------------------------------
      
      Operation could destabilize the runtime. 
      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.Security.VerificationException: Operation could destabilize the runtime.
      
      Source Error: 
      
      Line 72:             int pageSize = 3;
      Line 73:             int pageNumber = (page ?? 1);
      Line 74:             return View(students.ToPagedList(pageNumber, pageSize));
      Line 75:         }
      Line 76:  
      
      Source File: C:\MSDN\Demo\C#\ContosoUniversity\Controllers\StudentController.cs    Line: 74 
      
    • The problem appears to be an incompatibility with VS 2012 in the PagedList NuGet package.  Updating the package resolves the error.  I'll upload a new version of the project with the updated package.
  • UnitOfWork and Repositories
    2 Posts | Last Post August 09, 2012
    • In the tutorial we create a generic repository to integrate the UnitOfWork but you also say that we should create Interfaces and repositories for the rest of the models if we are going use TDD.
      
      How this repositories interfaces would integrate with the generic repository?
      Or they dont integrate and only exist for TDD use?
      
      Thanks and it was a great tutorial.
    • You would create one interface for the generic repository the same way you create one interface for each non-generic repository, and one interface for the unit of work class. You would then call the generic repository through the interface, as you would with the non-generic repositories. In other words, if you create the generic repository to handle 5 different entities, you don't create 5 interfaces, you just create one for the generic repository. But if you create a derived class from the generic repository to handle special needs for one entity, you would create an interface for that also. 
  • Unit Testing w/MVC
    2 Posts | Last Post July 11, 2012
    • First off, this is an awesome example.  I have downloaded this and the pure ASP.NET Web Pages sample.  Why does this sample not have an example of Unit Testing whereas the Web Pages sample does?  I am developing an MVC 3 application for my business and used about 75% of the code in here, but ended up using code from the MVC 3 book from Steve Sanderson because he had unit testing included.  I love the PagedList in ContosoUniversity, but not sure how to use it for unit tests.  Anywhere else that has the ContosoUniversity example with a unit test or 2 that I can go to and check out?
      
      Thanks for a great example!
    • I'm glad to hear that you've found the sample helpful. I don't remember now why we decided not to include unit testing in the MVC series, but I suspect it was because it was already getting fairly long and unit testing seemed relatively peripheral to the main goal of showing how to use Entity Framework. We are currently prioritizing work for the remainder of this year, and updating this tutorial series is one of the tasks being considered. I'll add unit testing as one of the proposed enhancements when we update, but it's unsure right now how much time is available for that or if it might get delayed again by higher priority work.
  • DB not working
    2 Posts | Last Post June 11, 2012
    • I'm sure it is me somehow, but I am just trying to get this to work on my VS 2010 Prof edition but keep getting this error:
      
      "Unable to find the requested .Net Framework Data Provider.  It may not be installed."
      
      I have SQLExpress and SQL CE installed so I don't know what else could be wrong. Also, when I look in the app_data folder, the db doesn't show up??? I don't see the mdf. In the physical dir I see sdf. I always have terrible luck with these db files, so please help me out. I've tried both the VB and C# versions, both do not work on my VS 2010. Am I missing the mdf?
    • You should only need SQL Compact to be installed. One thing you might try, though, in case there's some problem with your installation of SQL Compact, is to install the EF NuGet packages in the project. The NuGet package names are SQL ServerCompact, EntityFramework, and EntityFramework.SqlServerCompact.
  • 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.
11 - 20 of 27 Items