【发布时间】:2015-12-23 16:03:20
【问题描述】:
我使用的是 EF 6.1.3 Code First。
我有 2 节课:
- 员工
- 决定
员工从一个文件中加载,每个文件都包含一个唯一的EmployeeID。
我的应用程序允许用户输入和保存有关这些员工的新决策。 但是,当 EF 将新决策保存到 DBContext 时,EF 会使用 DB 生成的值覆盖 Employee 的 EmployeeID。
所以,我将属性DatabaseGeneratedOption.None 如下添加到Employee.EmployeeID:
[Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
接下来,我删除了数据库,删除了所有迁移,并添加了新迁移。
但是,此迁移将identity(“指示数据库在插入期间是否会为此列生成值”)设置为true:
CreateTable(
"dbo.Employees",
c => new
{
EmployeeID = c.Int(nullable: false, identity: true),
...所以,这没有帮助。
手动编辑此迁移(即,将 identity 设置为 false)会在尝试保存上下文时引发错误:
InnerException = {"Cannot insert the value NULL into column 'EmployeeID', table '[...]DBContext.dbo.Employees'; column does not allow nulls. INSERT fails. The statement has been terminated."}
...尽管上下文的 Local DBSet 中的 EmployeeID 是正确的(不为空,未生成)。
我一直在寻找解决方案,但我能想到的只是次优解决方法:向 Employee 添加另一个非关键属性。
我尝试过的其他方法,无济于事:
使用自动迁移
将 [ForeignKey("EmployeeID")] 添加到 Decision.Employee
编辑: 根据 E-Bat 的要求,以下是我的实体的摘录:
public class Employee : INotifyPropertyChanged
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
private int _employeeID;
public int EmployeeID
{
get { return _employeeID; }
set
{
if (value != _employeeID)
{
_employeeID = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(nameof(EmployeeID)));
}
}
}
}
[等等]
public class Decision : INotifyPropertyChanged
{
private int _decisionID;
public int DecisionID
{
get { return _decisionID; }
set
{
if (value != _decisionID)
{
_decisionID = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(nameof(DecisionID)));
}
}
}
}
private Employee _employee;
public Employee Employee
{
get { return _employee; }
set
{
if (value != _employee)
{
_employee = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(nameof(Employee)));
}
}
}
}
[等等]
【问题讨论】:
-
发布这些实体的相关代码以及映射设置
-
+1 不是针对问题,而是针对您问题的详细程度。这写得很好,SO 社区很容易理解
标签: c# entity-framework ef-code-first primary-key entity-framework-migrations