,ef-code-first,entity-framework-6 , Entity Type 'AstNode' has no key defined

Entity Type 'AstNode' has no key defined



I'm porting a data model from EF4 to EF6 Code First. I'm getting the following message when the database creation is attempted. I'm at a loss to understand what is causing this. I don't have any Context, AstNode or JSParser entities. It is also not looking in the Models namespace:

var context = QPDataContext.Create();
var session = context.DataSessions.FirstOrDefault(ds => ds.DataSessionId = sessionId); 

Throws this exception:

{"One or more validation errors were detected during model generation:

   QPWebRater.DAL.Context: : EntityType 'Context' has no key defined. Define the key for this EntityType. 
   QPWebRater.DAL.AstNode: : EntityType 'AstNode' has no key defined. Define the key for this EntityType.
   QPWebRater.DAL.JSParser: : EntityType 'JSParser' has no key defined. Define the key for this EntityType.
   (many more similar errors snipped). 

Here is my database context (I've simplified it a bit):


using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Core;
using System.Data.Entity.Validation;
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using Microsoft.Ajax.Utilities;
using QPWebRater.Models;
using QPWebRater.Utilities;

namespace QPWebRater.DAL
    public class QPDataContext : DbContext
        public QPDataContext()
            : base("DefaultConnection")
            Database.SetInitializer<QPDataContext>(new CreateDatabaseIfNotExists<QPDataContext>());

        public static QPDataContext Create()
            return new QPDataContext();

        public DbSet<DataSession> DataSession { get; set; }
        public DbSet<Document> Documents { get; set; }
        public DbSet<Driver> Drivers { get; set; }
        public DbSet<Location> Locations { get; set; }
        public DbSet<Lookup> Lookups { get; set; }
        public DbSet<Quote> Quotes { get; set; }
        public DbSet<Vehicle> Vehicles { get; set; }
        public DbSet<Violation> Violations { get; set; }


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace QPWebRater.Models

    public partial class DataSession
        public DataSession()
            this.Vehicles = new HashSet<Vehicle>();
            this.Drivers = new HashSet<Driver>();

        public string DataSessionId { get; set; }
        public System.DateTime Timestamp { get; set; }


    public partial class Document
        public int DocumentId { get; set; }
        public int QuoteId { get; set; }
        public string DocumentType { get; set; }
        public string Url { get; set; }
        public string Description { get; set; }

        public virtual Quote Quote { get; set; }

    public partial class Driver
        public Driver()
            this.Violations = new HashSet<Violation>();

        public int DriverId { get; set; }
        public string DataSessionId { get; set; }


I solved this by examining all of the DbSet definitions. I had pared down the data model while also upgrading it. I had removed the Lookup model class but neglected to also remove the DbSet<Lookup> Lookups { get; set; } property.

This resulted in the class being resolved as Microsoft.Ajax.Utilities.Lookup. At runtime, EntityFramework tried to add a corresponding database table which failed miserably. If you are running into a similar problem then double check the generic types in your DbSet properties.


Error while connecting to database in code-first Entity Framework

I am getting following error message when context is trying to connect to database using code-first approach of Entity Framework System.Data.Entity.DbContext' does not contain a definition for 'System' and no extension method 'System' accepting a first argument of type 'System.Data.Entity.DbContext' could be found (are you missing a using directive or...

MVC route attribute no controller,,
I'm building an intranet where I have the following home controller: [Route("{action=index}")] public class HomeController : Controller { public ActionResult Index() { return View(HomeModelBuilder.BuildHomeModel()); } public ActionResult FormsHome() { return View(HomeModelBuilder.BuildFormsHomeModel()); } } I'm trying to get my forms homepage to have a url of http://intranet/forms so I thought I...

Knockout js unable to bind data using observableArray

I am trying to display all the employees in the database and I am unable to achieve it. My JS, var EmployeeKoViewModel = function () { var self = this; self.EmpId = ko.observable(""); self.Name = ko.observable(""); self.City = ko.observable(""); self.Employees = ko.observableArray([]); GetEmployees(); function GetEmployees() { $.ajax({ type: "GET", url:...

How to automatically update the database on application start up

A run time error occurs when i run my code asking me to do a code migration to update my database. I am not sure how to do this, can anyone help me? The model backing the 'ApplicationDbContext' context has changed since the database was created. Consider using Code First...

EF Code first - many to many relation mapping table with extra columns

I am having a User Model and and a Group Model. User and Group share a many to many relationship. In when I translate this to table, I want to have a mapping table. I am using the following to achieve this. modelBuilder.Entity<UserGroup>() .HasMany(a => a.Users) .WithMany(b => b.UserGroup) .Map(mc...

In MVC Razor, how can I correctly add querystring parameters to an html.actionlink?,razor,
I have an MVC Razor page where I am trying to add a querystring parameter to the URL. <td> @Html.ActionLink(item.Student_Name, "Index", "FourCourseAuditDetails", new { filterByStudent = item.Student_Name}) </td> My desired outcome is: http://[server]/FourCourseAuditDetails/Index?filterByStudent="[item.Student_Name]", but when I test out the page, the anchor href attirubte looks like this: http://[server]/[route of current...

How to augment actionlink with route values at runtime with JavaScript in ASP.NET MVC 5?

I have this ActionLink. @Html.ActionLink("Link", "action", "controller", null, htmlAttributes: new {@class = "menuLink"}) I have to set routeValues to null because I don't know the value at compiletime. They are recieved from the selectedvalue of some dropdowns at runtime. Hence, I am trying to augment the routevalues at runtime with...

Convert string value to english word

I'm trying to figure out / where to start in regards to this situation say for example I enter $127.45 in to a textbox I would expect the application to spit back one hundred and twenty-seven dollars and forty-five cents The word will then be placed on a document and...

How do I properly send __RequestVerificationToken with an ajax request in MVC5

I'm trying to send an ASP.NET AJAX request to my application. In the application's controller, I have: [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Edit([Bind(Include = "ID,Name,Instructions,Glass,Notes")] Drink drink, [Bind(Include= "ID,Amount,Brand,IngredientID,DrinkID")] IEnumerable<DrinkIngredient> DrinkIngredients) { if (ModelState.IsValid) { //and so on my javascript looks like this: console.log($('#editDrinkForm').serialize()) var x = new XMLHttpRequest(); x...

When should I use ViewBag/model?

I think that using ViewBag is faster than model. My example is: In the action: public ActionResult MyAction() { ViewBag.Data = (from m in myDatabase.myTable select m).ToList(); } In the view: @foreach(var item in ViewBag.Data) { <tr> <td>@item.myColumn</td> </tr> } By using model: [Table("tbl_mytable")] public class MyTable() { public int...

Future plans to consider for mvc 5.2 web application, with releasing mvc6 (vnext),,,,
I need to get any ideas of how i should be managing our previous MVC 5.2 web application.. now i am using mvc-5.2 with entity framework 6.0. and i want to start phase-2 for some of these projects. so should i consider upgrading my mvc 5.2 to be...

How to get routevalues from URL with htmlhelpers or JavaScript?

I have this MVC MapRoute routes.MapRoute( name: "Authenticated", url: "{controller}/{action}/{foo}/{bar}", defaults: new { controller = "Home", action = "WelcomePage", Foo = "0", Bar = "0" } ); And URL http://localhost/mysite/controller/action/2/1 How can I with JavaScript recieve the 2 and 1? I would prefer a solution with as little substring work...

how to use where with list of string

I have List Of string Like as "one" , "two" , "three" ,... I want Search From DataBase and select All Items Where have At least On of them , I wnat do this by Entity framwork , To do this I use : if (SearchVM.Tags.Count > 0) //SourceList= SourceList.Where(x=>x.Tags.Where(...));...

MVC5 Scaffolding Dropdowns Out the Box,,poco,html.dropdownlistfor,
I want to view, edit and create with drop-down list of my lookup relationships. Sometimes this works, sometimes it doesn't. It's a mystery that I'm hoping can be definitely solved here. Here's my POCO's for the lookup public class Color { public int Id { get; set; } public string...

Entity Framework, Code First, Update independent association (Collection)

to explain the problem I have a simple model with a class Person: public class Person { public int Id { get; set; } public virtual string Name { get; set; } } and a class School with a collection of Persons: public class School { public int Id {...

How to append Urls in angular routing?,angularjs,,angularjs-ng-repeat,angular-ui-router
How to do url(string) cocatenation in angular routing. Please refer the below snippet to understand my question. app.config(['$routeProvider', '$location'], function($routeProvider) { when('/', { templateUrl: '/AlbumsList.html', controller: 'a1Ctrl' }). when('/albums/:albumName', { templateUrl: 'AlbumsList.html', controller: 'b1Ctrl' }) }) app.controller('a1Ctrl', function($scope, $http) { $scope.albums = function() { //ajax getting data from server }...

Web API AuthorizeAttribute does not return custom response

How can I make IsAuthorized return my custom object while function returns false? In my WebAPI project I have a class like; public class CustomAuthorizeAttribute : AuthorizeAttribute { protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext) { StandardWebAPIResponse invalidUserResponse = new StandardWebAPIResponse() { code = (int) Constants.ErrorCodes.InvalidCredentials, data = "InvalidCredentials.", StatusCode = HttpStatusCode.Unauthorized...

string.Format is not giving correct output when INR currency symbol (Rs.) come to display

While display bank transaction data to INR currency symbol (Rs.), output is not coming correct way. I need to display currency symbol along with 2 decimal points with thousand separator. I have tried so far1: column.PropertiesEdit.DisplayFormatString = string.Format("{0} #,0.00", Model.CurrencySymbol); I have used DevExpress MVC GridView. Current output when INR...

EPPlus export model to Excel: System.NullReferenceException

I have an MVC view that correctly displays a model. Now that I have been asked to put an Export to Excel function on that page, I heard about EPPlus and gave it a try. From this site I thought I had something that would simply do the job. After...

Web API Basic Auth inside an MVC app with Identity Auth

So I have a C# MVC app using Identity for its authentication. I now have a need to expose a few things via Web API to some of my clients. Instead of building a separate app, project, deployment... I've simply added an API Controller to my existing project. To keep...

Adding column in Entity Framework 6.1 - Many-To-Many - Code First

Just as an example I'm using the code from this article on codeproject: Im trying to do something similar in my code but I also want a quantity property, so: One course can have many persons One Person can have many courses Each person can choose a quantity of...

How to use ajax to post json string to controller method?

I want to be able to post a json string to a control action but it's always receive the string as null. If I create a view model for the controller method, it works, but that's not what I want since there will be too much view models to maintain....

Produce different serialized JSON for a given class in different scenarios

Update 1: for reasons I won't go into, I want to avoid having anything other than the properties to be persisted in my entity objects. This means no extra properties or methods... I have an entity called Entity1 with (say) 10 public properties. In one place in my code I...

Best approach to upgrade MVC3 web app to MVC5?

I have a web application which runs on Azure which is currently running MVC3/C#, EF6.1, .NET4.5. I would like to upgrade it to MVC5 to be: a) Current b) Get benefit of new features c) Get Performance gains. This is a part of a performance project, so hopefully there will...

How detailed should your repository be? Testing issues [closed]

In my controller, I have something like this: class HomeController { [AllowAnonymous] public ActionResult Index() { HomeViewModel viewModel = new HomeViewModel(); viewModel.FieldSearchCriteria = new SearchCriteria(); viewModel.Blogs = this.unitOfWork.BlogRepository.GetAllPublishedBlogs(1, 2, "PublishDate", SortDirection.DESC, null).ToList(); viewModel.FieldWanteds = this.unitOfWork.FieldWantedRepository.GetAllFieldWanteds( 1, 2, "CreatedAt", SortDirection.DESC, null ).ToList(); viewModel.Fields =...

MVC: after export to excel, index action result is not getting called,export-to-excel
I have one MVC application, in which export to excel functionality is given. I want to redirect Index action once export is finished. I have written below code but it not redirected to index action. what i missed here ? output = new MemoryStream(); workbook.Write(output); Response.ContentType = "application/"; Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}",...

MVC5 Login to custom Database,authentication,login,,owin
What if you have your own database and a BAL (Business Access Layer) and don't want to use DefaultConnection and the template ASPNET database tables but my own user tables? How can you use a custom database? ConnectionString: public class AppDbContext : IdentityDbContext<AppUser> { public AppDbContext() : base("DefaultConnection") { }...

Convert SQL to linq statement

I would like to convert the SQL syntax below to a linq statement to get a single boolean result back. The SQL is checking if a user exists in a current role. select case when exists (select 1 from Global.Application as a join Global.Role as r on a.ID = r.ApplicationId...

Entity Type 'AstNode' has no key defined,ef-code-first,entity-framework-6
I'm porting a data model from EF4 to EF6 Code First. I'm getting the following message when the database creation is attempted. I'm at a loss to understand what is causing this. I don't have any Context, AstNode or JSParser entities. It is also not looking in the Models namespace:...

How to upgrade mvc2 to mvc5?,,
I've got an old project from a friend that he wants me to do redo. How ever that project is written in mvc2. So When I try to open it in visual studio 2013 I can errors. Saying the file is incompatible. How would I go ahead and fix...

MVC throwing HTTP 404 error

I am completely stuck and confused why it works with one View to Controller but not the other one. The one that works: public class HomeController : Controller { // GET: Home IAuthenticationManager Authentication { get { return HttpContext.GetOwinContext().Authentication; } } public ActionResult Index() { return View(); } [POST("login")] [ValidateAntiForgeryToken]...

Store does not implement IUserLockoutStore,
I'm trying to implement own DAL for Identity 2.0 with functionality that I need. I don't need Account Lockout functionality. But When I try to call var result = await SignInManager.PasswordSignInAsync(model.Login, model.Password, model.RememberMe, shouldLockout: false); I get System.NotSupportedException:Store does not implement IUserLockoutStore<TUser>. So why should I need to implement...

Why is KnockoutJS not showing the same number of objects as my Web API controller?

The solution was the same as in this question: How to get an observableArray's length? ...but the question itself is unique so anyone in the same situation will hopefully have an easier time finding the answer than I did. I'm fairly new to Knockout and to Web API. I've built...

Embedding a Silverlight App into a MVC

I decided to convert the WPFs into a Silverlight applications. My only problem is trying to get it to display the silverlight application in my MVC web browser. I added all of my silverlight projects into my MVC project. I am just not getting it to show my silverlight application....

MvcSiteMapProvider - Enhanced bootstrap dropdown menu

I'm trying to build a menu like this: For reference I'm using this library @Html.MvcSiteMap().Menu("BootstrapMenuHelperModel") @model MenuHelperModel <nav class="navbar" role="navigation"> <div class="container-fluid menu-container"> <div class="collapse navbar-collapse"> <div class="navbar-header"> <span class="navbar-brand">FAR BACKOFFICE</span> </div> <ul class="nav nav-pills"> @foreach (var node in Model.Nodes) { if...

Linq Conditional DefaultIfEmpty query filter

I have a query as below: bool variable = false//or true var query = from e in _repository.GetAll<Entity>() from u in e.Users where (e.AuditQuestionGroupId != null ? e.AuditQuestionGroupId : 0) == this.LoggedInEntity.AuditQuestionGroupId from p in e.PractitionerProfiles.DefaultIfEmpty() select new { entity = e, user = u, profile = p }; This...

Entity Framework Code First - Optional/required two-way navigation

I have a code first model similar to the following: public class TestContext : DbContext { public DbSet<Class1> Class1s { get; set; } public DbSet<Class2> Class2s { get; set; } } public class Class1 { public int Class1Id { get; set; } } public class Class2 { public int Class2Id...

Entity Framework code-first: querying a view with no primary key

Our customer has given the access to views in which there is no primary key is defined. I know Entity Framework needs a primary key for table to identify. But for views not having primary key is it still possible to query. I try to find but always Entity Framework...

Inherited Property of Model is always returning Null Value

I have a view which displays a radiobutton list on left side of the page and it also loads a partialview on right side of the page which consist of various filters to be selected before displaying a report in a popup window. The problem is that the property named...

EPPlus: how can I assign border around each cell after I apply LoadFromCollection?

In my export ActionResult I was able to load the model into my ExcelPackage. Where I am having trouble is assigning a border around each cell once LoadFromCollection is applied. While the AutoFitColumns correctly applies, the border style I applied only works on Cells["D1"], but not on the table. BorderAround...

MVC/Razor: Error at Viewbag.Title

I have two methods: public ActionResult Index() { var propList = db.Properties .Where(x => x.SiteVisibilityFlags.HasFlag(Enums.SiteVisibilityFlags.Corporate) || (x.SiteVisibilityFlagsOverride == true && x.SiteVisibilityFlagsOverrideValue.HasFlag(Enums.SiteVisibilityFlags.Corporate))) // just ones visible to 'Corporate' .ToList(); // Use view model var pDVMs = DomainModelsToViewModels(propList); return View(pDVMs); } public ActionResult Region(string id) // (regionId/marketId) { // make sure to...

MVC 5 - Validate a specific field on client-side

I want to populate a city/state drop down list based on the postal code a user types into a textbox. So when the text changes, I'm going to make an ajax call to retrieve the data. However, I only want to perform that ajax request for valid postal codes. The...

ApplicationUser ICollection member not being saved in DB

I've added some properties to ApplicationUser, and two of them are ICollection's. When I use Update-Database it doesn't generate columns for these two members. So, what am I missing here? I imagine it's very basic. I'm used to working with Hibernate in Java, where it generates a new table for...

Getting users from another AD Domain using PrincipalContext

How would I get users from an AD Group which contains users from different domains. For example, I have 2 domains in my active directory, and I have an AD group called TestGroup which contains users from both the domains. Domain1 users: TestUser1, TestUser2 Domain2 users: TestUser3, TestUser4,...

LINQ: Searching inside child entities

I have 'Property' objects with 'BayOption' child objects. I need the site search to search through the child BayOptions as well as the Properties and return Properties if the search criteria matches the child or parent. A Property can have multiple BayOptions (and usually does). I was unsure if .Select...

Add azure db to mvc5 project,azure,visual-studio-2013,,sql-azure
I have a MVC 5 project using visual studio 2013. How can I add/create a database in azure from visual studio so that EF6 code first can just use and create the models? I've been browsing server explorer but there is nothing there related to azure....

Asp.Net MVC 5 + Bootstrap. How make inputs fit screen width?

I really don't know what I'm doing wrong. I want my textboxes with same size of my buttons below. I already tried change a lot in the cshtml but without success. Below my cshtml file: @model SomeModel.Models.LoginViewModel <div class="row"> <div class="col-md-8 col-sm-12 col-xs-12"> <section id="loginForm"> @using (Html.BeginForm("Login", "Account", new {...

MVC 5 OWIN login with claims and AntiforgeryToken. Do I miss a ClaimsIdentity provider?,,razor,,claims-based-identity
I'm trying to learn Claims for MVC 5 OWIN login. I try'ed to keep it as simple as possible. I started with the MVC template and inserted my claims code (see below). I get an error when I use the @Html.AntiForgeryToken() helper in the View. Error: A claim of type...

ED Code First One to Many Relationship Issue - ASP Identity

I'm configuring a database for ASP Identity and I've hit a snag. I'm looking to create a One to Many relationship between two tables, which are ApplicationUser & OrganisationUnit. An OrganisationUnit can have multiple ApplicationUsers, with an ApplicationUser only belonging to one OrganisationUnit When I add a migration and update...