Jus*_*ser 5 entity-framework ef-code-first asp.net-mvc-4 asp.net-web-api visual-studio-2012
我有一个 MVC4/Web API 项目,带有实体框架、代码优先数据模型。当我尝试使用数据上下文和模型创建具有读/写方法的新 API 控制器时,我收到一条警告,提示“对象引用未设置到对象的实例”。
我做了一些搜索,发现一些原因是 .csproj 文件中的项目类型 Guids 不正确、MvcScaffolding nuget 包的安装不完整以及安装 Powershell 3 的一个建议。
我已经确保我所有的项目类型 guid 都是正确的,确保正确安装了 MvcScaffolding 包,我什至安装了 Powershell 3。
这些都没有解决我的问题。我能想到的只是我的数据上下文/模型有问题,尽管它创建的表/关系很好。代码如下:
语境:
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; }
}
Run Code Online (Sandbox Code Playgroud)
模型:
[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; }
}
Run Code Online (Sandbox Code Playgroud)
连接字符串:
<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" />
Run Code Online (Sandbox Code Playgroud)
对此的任何帮助将不胜感激,因为我已经尝试了所有建议,但我仍然无法创建带有脚手架的控制器。气死我了!
谢谢!
发现问题了。在我的模型中,我有一个具有自定义枚举类型的属性,该属性位于我的业务项目中。在我的服务项目中,我引用了我的数据模型项目,但没有引用业务项目。因此,添加对模型和业务项目的引用使我能够很好地添加脚手架控制器。
我知道这似乎很明显,但它给你的错误消息毫无帮助!
无论如何,我希望这可以帮助任何遇到同样问题的人,并且无法使用其他建议来解决它。