"Object reference not set to an instance of an object" when creating a new Web API controller with EF Scaffolding in Visual Studio 2012 - entity-framework

I have an MVC4/Web API project, with an Entity Framework, Code First data model. When I try to create a new API Controller with read/write methods using a data context & model, I get an alert saying "Object reference not set to an instance of an object".
I've done a bit of searching and found that some causes are incorrect project type Guids in the .csproj file, incomplete installation of the MvcScaffolding nuget package and one suggestion of installing Powershell 3.
I have made sure all my project type guids are correct, made sure the MvcScaffolding package is installed correctly, and I've even installed Powershell 3.
None of this has solved the problem for me. All I can think is there is a problem with my data context/model although it created the tables/relationships fine. Code below:
Context:
public class PropertySearchContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Property>().HasRequired(p => p.Office).WithMany(o => o.Properties).HasForeignKey(p => p.OfficeId);
}
public DbSet<Office> Offices { get; set; }
public DbSet<Property> Properties { get; set; }
}
Model:
[Serializable]
public class Property
{
public int PropertyId { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string Town { get; set; }
public string County { get; set; }
public string Postcode { get; set; }
public int Bedrooms { get; set; }
public int Bathrooms { get; set; }
public string UmbracoNodeId { get; set; }
public string MainImageUrl { get; set; }
public string ListingImageUrl { get; set; }
public int TotalImageCount { get; set; }
public PropertyType PropertyType { get; set; }
public PropertyStatus PropertyStatus { get; set; }
public long Price { get; set; }
public string ListingUrl { get; set; }
//Navigation Properties
public int OfficeId { get; set; }
public virtual Office Office { get; set; }
//Meta properties
public DateTime CreatedAt { get; set; }
public string CreatedBy { get; set; }
public DateTime UpdatedAt { get; set; }
public string UpdatedBy { get; set; }
}
Connection String:
<add name="PropertySearchContext" connectionString="Data Source=MERCURY\SQLEXPRESS;Initial Catalog=DATABASE_NAME;Integrated Security=False;User ID=dbFakeUser;Password=fakePassword;Connect Timeout=10" providerName="System.Data.SqlClient" />
Any help with this would be greatly appreciated as I've tried every suggestion and I still can't create a controller with scaffolding. Driving me mad!
Thanks!

Found the problem. In my model, I had a property with a custom enum type, which was in my business project. In my service project, I had my data model project referenced but not the business project. So adding a reference to the model AND business project allowed me to add scaffold controllers fine.
Seems obvious I know, but the error message it gives you is so unhelpful!
Anyway, I hope this helps anyone having the same problem, and can't fix it using the other suggestions.

I am adding an answer as my problem was the same and my solution was different. It had no relation to the referenced assemblies. First of all, I believe it only happened because the Web API project had just been created (from scratch).
I will give you some code examples based on the OP code. First, my context class that inherits from DbContext had to call the base constructor passing as argument the connection string name:
public class PropertySearchContext : DbContext
{
public PropertySearchContext () : base("name=PropertySearchContext")
Second, the Web API application would internally look inside Web.config for a connection string named PropertySearchContext. Web.config already comes with a DefaultConnection, so I just had to add a new one with the proper name and settings:
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\DATABASE_NAME.mdf;Initial Catalog=DATABASE_NAME;Integrated Security=True" providerName="System.Data.SqlClient" />
<add name="PropertySearchContext" connectionString="Data Source=MERCURY\SQLEXPRESS;Initial Catalog=DATABASE_NAME;Integrated Security=False;User ID=dbFakeUser;Password=fakePassword;Connect Timeout=10" providerName="System.Data.SqlClient" />
</connectionStrings>
note: the OQ already has that connection string.
Third and finally, I had to build the WebAPI project. Once successful, the creation of controllers worked fine.

I get this error if I am attempting to Scaffold a controller with views for a Model that does not contain a default constructor(one that does not need parameters). Add one to the model and try again. This has bitten me more than once.
The newer compilers works just fine without one, as if it does not see one it just inserts one for you. However the scaffold operation needs that default constructor be actually declared in code to operate correctly. I just wish it gave you a better explanation when you get the error.
So for the original post simply adding this to the class :
public Property(){}
should do the trick.

If you have more than one project in your solution try to rebuild all.

This answer depends on many things. On my case I didn't have a problem with the model itself. After long hours looking I discovered that another project, which was being referenced on my MVC .NET website, was the one stopping the scaffolding from running correctly.
What I am doing (kind of tedious) is to remove the reference (breaks many things meanwhile), Add the controllers/views that I need, then add the reference again and voila. No "Object Reference" error.
Hope this works for you

Related

Entity framework "Field required" Error but works fine in debuuging

I have got a strange error in entityframework when I am trying to update an entity which uses some virtual (lazy load) properties. I retrieve the entity from the database and change a one to one property in that then try to update it again.The exception for some of the virtual properties is The field is required while others don't have this error.
What makes everything even more strange is that when I try to inspect the entity in debug mode the code just works fine and I don't face any errors at all.
Has anyone else experienced such behavior?
Thanks
Here is what code looks like:
public class IndependenceCheck : ModelBase
{
[Key]
public int IndependenceCheckID { get; set; }
public int PrincipalCompanyID { get; set; }
[Required]
[ForeignKey("PrincipalCompanyID")]
public virtual Company PrincipalCompany { get; set; }
[ForeignKey("OrganizationAddressID")]
[Required]
public virtual Address OrganizationAddress { get; set; }
}
There are much more fields in model, while I try to update no errors for PrincipalCompany occurs but for OrganizationAddress I got the required field error.

Why MVC does autoupdate of EF Model Classes?

I generated Entity Model from my database in my MVC5 App.
When I try to add [DispalyName] to some properties it works fine, but after some time app refreshes this class by itself and removes all my custom code
public partial class Patient
{
public Patient()
{
this.PatientDetails = new HashSet<PatientDetail>();
}
public int PatientID { get; set; }
[DisplayName("Last Name")]
public string LastName { get; set; }
public string FirstName { get; set; }
public virtual ICollection<PatientDetail> PatientDetails { get; set; }
}
Why MVC does it and how to disable that?
I believe since you're using Database first, the entities will get completely re-created every time you refresh, thus you lose your custom attributes.
Also, to go off of Joe's comment, you should make a view model and put your [Display] attributes there and not directly on the entity.

Value cannot be null. Parameter name: entitySet

I have a fairly standard setup with simply POCO classes
public class Project
{
public int ProjectId { get; set; }
public string Name { get; set; }
public int? ClientId { get; set; }
public virtual Client Clients { get; set; }
}
They use an interface
public interface IProjectRepository
{
IEnumerable<Project> Projects { get; }
}
and are constructed as a repository for ninject to bind to
public class EFProjectRepository : IProjectRepository
{
private EFDbContext context = new EFDbContext();
public IEnumerable<Project> Projects
{
get { return context.Projects; }
}
}
The actual context is a simply DbContext
public class EFDbContext : DbContext
{
public DbSet<Project> Projects { get; set; }
}
When I try and enable code first migrations I get the following error
I have done this exact process with other projects and there as never been an error. This is connecting to a local Sql Server Database. There does not seem to be a problem with the connection string. I have searched for this error online but the solutions seem to answer questions that do not directly relate to my setup.
I had the same issue and the cause was a POCO class that had a property of type Type.
Late to the game...but if it helps...
I had this same problem, everything was working fine, but this issue appeared, I added the following to one of my classes
public HttpPostedFileBase File { get; set; }
which seemed to break it.
I ensured I didn't map this to the database by using the following:
[NotMapped]
public HttpPostedFileBase File { get; set; }
You need to add the following using statement:
using System.ComponentModel.DataAnnotations.Schema;
Hope this helps
This problem can occur if one of the POCO classes was not declared in the DbContext.
I added them and the error went away
I had changed the name of the Task POCO class because of its association with a built in .NET name System.Threading.Tasks. However I had not changed this in the "TaskTimeLog" POCO where there was a relation. When going through the code the "Task" property in the "TaskTimeLog" POCO was not showing an error because it was now attached to that threading keyword and the reason I had changed the name in the first place.
I got this error:
Value cannot be null. Parameter name: entitySet
Turns out I was trying to join data from 2 different DbContexts.
var roles = await _identityDbContext.Roles
.AsNoTracking()
.Take(1000)
.Join(_configurationDbContext.Clients.ToList(),
a => a.ClientId,
b => b.Id,
(a,b) => new {Role = a, Client = b})
.OrderBy(x => x.Role.ClientId).ThenBy(x => x.Role.Name)
.Select(x => new RoleViewModel
{
Id = x.Role.Id,
Name = x.Role.Name,
ClientId = x.Role.ClientId,
ClientName = x.Client.ClientName
})
.ToListAsync();
The fix is to add ToList as shown. Then the join will happen in code instead of the database.
Only do this if you are OK with retrieving the whole table. (I know my "Clients" table will always be relatively small.)
For anyone not finding a resolution in the other answers, I got this error when I created a derived class from a class that had an instance in some model. The exception occurred on the first usage of my context in a request.
This is a stripped-down example that will reproduce the behaviour. Model is a DbSet in my context.
public class Model
{
public int Id { get; set; }
public Duration ExposureDuration { get; set; }
}
public class Duration
{
public int Value { get; set; }
public string Unit { get; set; }
}
//Adding this will cause the exception to occur.
public class DurationExtended : Duration
{ }
This happened during work in progress. When I changed the model property ExposureDuration to type DurationExtended, all was working again.
I had the same issue and it took quite a while to find out the solution.
In our case, we created a seperated project to handle the Entities and even if the default project in the Package Manager Console was the one handling the Entities, I need to set this project as the default project in order to make it work.
I hope this will help somebody else.
I got this error when I declared a variable of type Type - which is probably because is a complex type not supported by the DB.
When I changed it to string, the error went away
public class Sample
{
public int SampleID {get;set;}
public Type TypeInfo {get; set;} //This caused the error,
//because Type is not directly convertible
//in to a SQL datatype
}
I encountered this same issue and resolved like so:
Error in model class:
public class UserInformation
{
public string ID { get; set; }
public string AccountUserName { get; set; }
public HttpPostedFileBase ProfilePic { get; set; }
}
No error in model class
public class UserInformation
{
public string ID { get; set; }
public string AccountUserName { get; set; }
public string ProfilePicName { get; set; }
}
My issue was resolved once i updated the ProfilePic property type from HttpPostedFileBase to string. If you have a property that is not of type string, int, double or some other basic/standard type either replace such property or update to a type which SQL is more likely to accept.
Remove the line <Generator>EntityModelCodeGenerator</Generator> from your project file.
Check out this https://www.c-sharpcorner.com/UploadFile/5d065a/poco-classes-in-entity-framework/
I have some properties in "ExpenseModel", one of this was...
public virtual Type TypeId {get; set;}
which was causes the above same error because of "Type" propertyType,
so I changed "Type" => "ExpenseType" and it worked... :-)
public virtual ExpenseType TypeId {get; set;}
ExpenseModel.cs
public class ExpenseTypes
{
[Key]
public int Id { get; set; }
public string TypeName { get; set; }
public string Description { get; set; }
}
In my case I had to reference another model class called IanaTimeZone, but instead of
public virtual IanaTimeZone Timezone { get; set; }
out of rush I typed this:
public virtual TimeZone Timezone { get; set; }
and it compiled fine because VS thought it was System.TimeZone but EF6 was throwing the error. Stupid thing but took me a while to figure out, so maybe this will help someone.
To anyone else this might be helpful, I had a property TimeZone (the actual .NET TimeZone object) and this gave me the exact same error, not sure why but will dig deeper :)

Entity Framework Code first missing foreign key entities in WebAPI project

I'm afraid that if I include my code this post will get too long and too complicated, so I'll try and explain my problem. If however you'd like to see some code illustrating this problem, I'll be happy to add it afterwards.
I have a project, MVC4 project (Website.Web) that used entity framework code first. My entity classes is in a seperate project: Website.Domain
I have a NewsPost class:
public virtual int Id { get; set; }
public virtual string Subject { get; set; }
public virtual string Content { get; set; }
public virtual string ImageName { get; set; }
public virtual DateTime CreateTime { get; set; }
public virtual int CreatedById { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
And my comments class looks like this:
public virtual int Id { get; set; }
public virtual int CreatedById { get; set; }
public virtual DateTime CreatedTime { get; set; }
public virtual string Content { get; set; }
Now in my MVC project, I have entity framework set up with some repository classes and ninject to seperate everything from my controllers. And when I do a "GetAll()" on my newsposts. The NewsPost.Comments will be filled with the comments that's associated with this newspost. It all works perfectly.
Now I got the idea that I'd like to use webapi, so I set up a new MVC basic project. I removed the views folder, and removed the models folder. Then I setup all the repositories here as well along with my entity framework dbcontext class. And enabled migrations on the project to allow me to use entity framework code first in the same fasion as the Website.Web project. I also referenced the same Domain classes as the web project.
Now here comes the problems. I tried doing a GetAll() on the newsposts, but when I inspect the list returned by GetAll(), I see that though it fetches all the news in the database, the COMMENTS are null. I'm pretty sure I have the Website.API set up the same way as my Website.Website.Web - So what am I missing?
I hope I have explained well enough. Again if you need any additional code or I need to clarify some points, I'll happily do this, I just didn't wanna make the question more complicated than it already is with too much code.

MVC 4 unique field model

I have been Googleing this and had no joy.
How do i add unique to a field in a code first approach in mvc4 .net
public class Religion
{
public int ReligionId { get; set; }
[Required]
[StringLength(200)]
public string Description { get; set; }
}
What would i need to add to description for this to work
you may use remote validation
review that link http://msdn.microsoft.com/en-us/library/gg508808(v=vs.98).aspx
simple and fast