2

In my mvc project I want to add a controller with views, using Entity Framework. I'm doing it with this tutorial http://www.asp.net/mvc/overview/getting-started/introduction/accessing-your-models-data-from-a-controller

Altough I keep getting this frustrating error enter image description here

I rebuilded my project many, many times. I tried some solutions I found in the Internet like Adding A New MVC 5 Controller with Views Using Entity Framework Scaffolding Error or reinstalling my nuget package, restarting Visual Studio, checking my conecctiong string (which seems alright btw), adding new model, etc. I have no idea what to do next, that's why I'm asking You for help.

I use:

  • Visual Studio 2013 on Windows 7
  • .NET Framework 4.6.2

My model code:

 public class UserResModel
   {
       [Display(Name = "ReservationID")]
       public int ReservationID { get; set; }

    [Display(Name = "Class")]
    public string ClassName { get; set; }

    [Display(Name = "When")]
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
    public DateTime ClassWhen { get; set; }

    [Display(Name = "Cancel reservation")]
    public bool CancelRes { get; set; }

}

8
  • Does your model have a default constructor? Could you show the model code? Commented Sep 25, 2016 at 23:44
  • What do you mean by that? I'm editing my question with the code Commented Sep 25, 2016 at 23:48
  • Set your web project to be the startup project Commented Sep 26, 2016 at 5:42
  • Unfortunately id didn't help :( I'm stil getting the same error Commented Sep 26, 2016 at 7:18
  • Have you tried my below answer? Commented Sep 26, 2016 at 8:34

1 Answer 1

0

You need to add the 'Key' attribute to your ReservationID property. Scaffolding requires a Key to work when it auto generates the controller code.

[Key]
[Display(Name = "ReservationID")]
public int ReservationID { get; set; }

Once you add that, rebuild the project and try the scaffolding again.

Sign up to request clarification or add additional context in comments.

2 Comments

Unfortunately id didn't help :( I'm stil getting the same error
If you are using the scaffold controller with entity framework and views option you will need to add a DbSet<ClassRes> auto property to your DbContext class as well (In the default project this is called ApplicationDbContext) once adding that do a rebuild and try again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.