我最近一直在学习asp.net MVC 5和EF6,我开始为我的视图开发视图模型,而不是将值填充到viewbag中。
我这是我的名为 EmployeeCreate
的视图模型namespace Rota.ViewModels
{
public class EmployeeCreate
{
public string FirstName { get; set; }
public string LastName { get; set; }
public IEnumerable<SelectListItem> Departments { get; set; }
}
}
我想要做的是创建[httpget] action method
,以便能够填充下拉列表
这是我的员工恩赐
namespace Rota.Models
{
public class Employee
{
public int ID { get; set; }
[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[ForeignKey("Department")]
[DisplayFormat(NullDisplayText="No Department")]
public int? DepartmentID { get; set; }
public virtual Department Department { get; set; }
public virtual ICollection<Schedule> Schedule { get; set; }
}
}
这是我的部门实体
namespace Rota.Models
{
public class Department
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int ID { get; set; }
[Required]
public string Name { get; set; }
public virtual ICollection<Employee> Employees { get; set; }
}
}
修改这是我的 DbContext 类
public class RotaContext : DbContext
{
public RotaContext() : base("RotaContext")
{
}
public DbSet<Department> Departments { get; set; }
public DbSet<Shift> Shifts { get; set; }
public DbSet<Employee> Employees { get; set; }
public DbSet<Schedule> Scheduled { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
public System.Data.Entity.DbSet<Rota.ViewModels.EmployeeCreate> CreateEmployeeViewModels { get; set; }
}
这是我的控制器
中的创建操作方法namespace Rota.Controllers
{
public class EmployeeController : Controller
{
//establish database connection
private RotaContext db = new RotaContext();
//GET: Employee/Create
[HttpGet]
public ActionResult Create()
{
EmployeeCreate ViewModel = new EmployeeCreate()
{
Departments = db.Departments.Select(department => new SelectListItem {
Value = department.ID.ToString(),
Text = department.Name
})
};
return View(ViewModel);
}
}
}
我遇到的麻烦是我一直收到这个错误:
在模型生成期间检测到一个或多个验证错误:
Rota.Entities.EmployeeCreate :: EntityType'EmployeeCreate'没有密钥 定义。定义此EntityType的键。 CreateEmployeeViewModels: EntityType:EntitySet'CreateEmployeeViewModels'基于类型 'EmployeeCreate'没有定义键。
我不知道为什么应用程序认为我的viewmodel是一个实体,我在这里看不到任何可能暗示的东西,据我所知,我以为我用数据库中的值填充了一个对象,并且因为viewmodel与除此之外的实体完全没有关联,它不需要密钥,因为它不需要唯一的标识符。
完整堆栈跟踪
[ModelValidationException:检测到一个或多个验证错误 在模型生成期间:
Rota.Entities.EmployeeCreate :: EntityType'EmployeeCreate'没有密钥 定义。定义此EntityType的键。 CreateEmployeeViewModels: EntityType:EntitySet'CreateEmployeeViewModels'基于类型 'EmployeeCreate'没有定义键。 ]
System.Data.Entity.Core.Metadata.Edm.EdmModel.Validate()+338
System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest,DbProviderInfo providerInfo)+370
System.Data.Entity.DbModelBuilder.Build(的DbConnection providerConnection)+288
System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)+94
System.Data.Entity.Internal.RetryLazy2.GetValue(TInput input) +248
1.Initialize()+72
System.Data.Entity.Internal.LazyInternalContext.InitializeContext() +543 System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +26
System.Data.Entity.Internal.Linq.InternalSet
System.Data.Entity.Internal.Linq.InternalSet1.get_InternalContext() +21 System.Data.Entity.Infrastructure.DbQuery
1.System.Linq.IQueryable.get_Provider() +64 System.Linq.Queryable.Select(IQueryable1 source, Expression
1选择器)+85 Rota.Controllers.EmployeeController.Create()in d:\开发\罗塔\罗塔\ \控制器EmployeeController.cs:87个
lambda_method(Closure,ControllerBase,Object [])+79
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext,IDictionary2 parameters) +242
2 参数)+39
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary
System.Web.Mvc.Async.AsyncControllerActionInvoker.b__39(IAsyncResult的 asyncResult,ActionInvocation innerInvokeState)+12
System.Web.Mvc.Async.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult) +139
1.CallEndDelegate(IAsyncResult的 asyncResult)+111
System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +112 System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +452 System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +15
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +37 System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +241
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +29
System.Web.Mvc.Async.WrappedAsyncVoid
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult)+53 System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +19
1.CallEndDelegate(IAsyncResult的 asyncResult)+111
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +51
System.Web.Mvc.Async.WrappedAsyncVoid
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +606 System.Web.HttpApplication.ExecuteStep(IExecutionStep step,Boolean&amp; completedSynchronously)+288
答案 0 :(得分:3)
SIGINT
您的上下文类中不需要这样做。如果你有这个,EF会尝试为你的viewmodel创建数据库对象。对于每个&#34; DbSet&#34;在上下文类中,EF创建DB对象。尝试删除它。