【发布时间】:2013-06-19 14:34:22
【问题描述】:
我提到了很多堆栈溢出问题,例如EntityType 'MyProfile' has no key defined. Define the key for this EntityType。并且提到的解决方案是定义[Key]属性。
即使添加了 [Key] 属性(当我尝试插入员工时),我仍然收到以下错误。我们如何解决这个问题?
EntityType 'Role' 没有定义键。定义此 EntityType 的键。
注意:即使在为 RoleID 添加设置器后,我也会遇到相同的错误。
public abstract int RoleID { get; set; }
注意:角色类是abstract 类
EF 代码优先
public static void InsertEmployees()
{
string connectionstring = @"Data Source=.;Initial Catalog=My19June_A;Integrated Security=True;Connect Timeout=30";
using (var db = new My19June_A(connectionstring))
{
Employee emp1= new Employee();
emp1.EmployeeID = 1;
emp1.IsActiveEmployee = true;
Employee emp2 = new Employee();
emp2.EmployeeID = 2;
emp2.IsActiveEmployee = true;
db.Employees.Add(emp1);
db.Employees.Add(emp2);
int recordsAffected = db.SaveChanges();
}
}
实体
public abstract class Role : IEntityWithKey
{
public EntityKey EntityKey { get; set; }
public abstract string RoleName { get; }
[Key]
public abstract int RoleID { get; }
}
public class ProgrammerRole : Role, IEntityWithKey
{
public EntityKey EntityKey { get; set; }
public override string RoleName { get { return "Programmer"; } }
[Key]
public override int RoleID { get { return 101; } }
}
public class ManagerRole : Role, IEntityWithKey
{
public EntityKey EntityKey { get; set; }
public override string RoleName { get { return "Manager"; } }
[Key]
public override int RoleID { get { return 102; } }
}
public class Employee : IEntityWithKey
{
public EntityKey EntityKey { get; set; }
private bool isActiveEmployee;
private IList<Role> roles;
public virtual IList<Role> RolesList
{
get
{
return roles;
}
}
public bool IsActiveEmployee
{
get
{
return isActiveEmployee;
}
set
{
isActiveEmployee = value;
}
}
public int EmployeeID { get; set; }
//Constructor
public Employee()
{
roles = new List<Role>();
}
public void TerminateEmployeeByRole(Role role)
{
if (RolesList == null)
{
//If employee has no role, make as inactive
isActiveEmployee = false;
}
else
{
//If employee has no role other than the input role, make as inactive
RolesList.Remove(role);
if (RolesList.Count == 0)
{
isActiveEmployee = false;
}
}
}
}
【问题讨论】:
-
我认为你需要一个
Role的公共设置器。 -
@DanielA.White 即使添加了 setter
public abstract int RoleID { get; set; },我也会遇到同样的错误 -
您不必在
Role的每个子类上显式设置IEntityWithKey。由于Role实现了该接口,因此假设它的所有子类也都实现了。 -
@MikeC 即使从子类中删除
IEntityWithKey也会出现同样的错误 -
为什么你的类实现
IEntityWithKey?有没有实际使用它的代码?
标签: c# .net entity-framework ef-code-first