【发布时间】:2015-03-10 12:24:40
【问题描述】:
当我调用 DbContext.SaveChanges() 时,它会将数据添加到我不想要的某个表中。
为了进一步解释这里是我的模型:
工作项
public class WorkItem
{
public long WorkItemID { get;set }
/* Some properties*/
public virtual IList<WorkItemSchedule> WorkItemSchedules {get;set;}
}
WorkItemSchedule
public class WorkItemSchedule
{
public long WorkItemScheduleID {get;set;}
public int PhaseID { get; set; }
/* Some properties*/
public virtual WorkItem WorkItem { get; set; }
public virtual Phase Phase { get; set; }
}
阶段
public class Phase
{
public int PhaseID {get;set;}
[MaxLength(250)]
[Index(IsUnique=true)]
public string PhaseName {get;set;}
/* Some prperies*/
}
从我的控制器保存 DbContext 更改时出现错误:
[HttpPost]
public ActionResult Generate(WorkItemScheduleViewModel viewModel)
{
WorkItem workItem = viewModel.WorkItem;
db.WorkItems.Add(workItem);
db.SaveChanges();
return RedirectToAction("Index", "WorkItem");
}
内部例外是:
无法在具有唯一索引“IX_PhaseName”的对象“dbo.Phase”中插入重复的键行。重复键值为 (Analysis)。\r\n 语句已终止。
我的问题是,我没有在 Phase 模型中做任何事情。因此,为什么 DBContext 监视器会为此更改(添加)。请帮忙。谢谢,
编辑
public class WorkItemManagerContext : DbContext
{
public WorkItemManagerContext()
: base("WorkItemManagerConnString")
{
}
public DbSet<Phase> Phases { get; set; }
public DbSet<WorkItem> WorkItems { get; set; }
public DbSet<WorkItemSchedule> WorkItemSchedules { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
这是我得到的内部异常:
Attaching an entity of type 'WorkItemManager.Models.WorkItemSchedule' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.
【问题讨论】:
-
WorkItemScheduleViewModel长什么样子? -
这只是一个收集workitemschedule的视图模型,我认为这与错误无关,因为我没有对dbcontext进行任何更改。
标签: c# asp.net-mvc entity-framework