我的代码位于Solution.Models.Worker
中:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace Solution.Models
{
public class Worker
{
public int AsmensKodas { get; set; }
public string Vardas { get; set; }
public string Pavarde { get; set; }
public DateTime GimimoData { get; set; }
public string Adresas { get; set; }
public bool AktyvumoPozymis { get; set; }
}
public class WorkerDBContext : DbContext
{
public DbSet<Worker> Worker { get; set; }
}
}
我通过添加更改了 web.config
文件
<connectionStrings>
<add name="WorkerDBContext"
connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Workers.mdf;Integrated Security=True"
providerName="System.Data.SqlClient"/>
</connectionStrings>
当我尝试使用“带有 View 的 MVC 5 Controller ,使用 Entity Framework ”和配置来添加 Controller 时
- 模型类:
Worker
(Solution.Models) - 数据上下文类:
WorkerDbContext
(Solution.Models) - Controller 名称:
WorkersController
我收到一条错误消息
There was an error running the selected code generator:
'Unable to retrieve metadata for 'Solution.Models.Worker.' One or more validation errors ware detected during model generation:
Solution.Models.Worker::EntityType 'Worker' has no key defined.
Define the key for this EntityType.
Workers:EntityType:EntitySet 'Workers' is based on type 'Worker' that has no keys defined.
有什么建议或者我做错了什么吗?
最佳答案
模型的属性之一应该是 Key。因此,将 [Key]
注释放在其中一个属性的顶部。像这样:
public class Worker
{
[Key]
public int AsmensKodas { get; set; }
public string Vardas { get; set; }
public string Pavarde { get; set; }
public DateTime GimimoData { get; set; }
public string Adresas { get; set; }
public bool AktyvumoPozymis { get; set; }
}
请不要忘记将此行添加到您的 using
指令中:
using System.ComponentModel.DataAnnotations;
此外,如果您的 Model
中有一个名称为 Id
的属性,则无需将 [Key]
属性添加到它。
关于c# - EntityType 'Worker' 没有定义键。定义此 EntityType 的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37501896/