首先,感谢您花时间阅读本文。尝试使用EF更新数据库时遇到了一些困难。我之前在另一个项目中使用过相同的方法,所以我认为这个问题可能在数据库中,但我只是没有看到它。数据库是SQL 2005中的遗留数据库,命名约定有很多不足之处,因此我一直通过HasColumnName方法将不一致的名称映射到更一致的名称:如。
modelBuilder.Entity<Case_Person_1>().ToTable("dbo.Case_Person_1");
modelBuilder.Entity<Case_Person_1>().Property(c => c.Id).HasColumnName("CaseNumber");
我将我的问题与其他类似的问题进行了比较,并进行了调查,以验证外键关系是否指向正确的方向,并且身份仅在PK上。当我没有显式设置数据生成选项时,该命令触发数据库,但它失败b / c我插入0作为我的键,选项显式设置为OFF。我可以在SQL事件探查器中看到这一点。当我添加Identity选项时,我得到了参照约束错误。
我已经失去了2天,而且我已经没有达到解决方案了,而且我的绳子已经结束了。 顺便说一句,在我的其他项目中,我不需要使用DatabaseGeneratedOption来装饰我的POCO,但是我没有在插入时遇到任何错误。我不知道这是不是SQL 2005的东西,或者我是否遗漏了其他东西......
完整的错误详情如下: 发现了System.Data.Entity.Infrastructure.DbUpdateException 消息=更新条目时发生错误。看到内心 细节例外。 Source = EntityFramework StackTrace: 在System.Data.Entity.Internal.InternalContext.SaveChanges() 在System.Data.Entity.Internal.LazyInternalContext.SaveChanges() 在System.Data.Entity.DbContext.SaveChanges() 在Scyfis.Ocyf.DataLayer.EntityExtensions.AddItem [T](T实体,DbSet
1 dbSet, DbContext context, Action
2 foriegnKeyUpdater)中 C:\ TFS \ CGProjects \ GOC \ SCYFIS \ PHTSY \开发\ SRC \数据层\助手\ EntityExtensions.cs:线 83 在Scyfis.Ocyf.DataLayer.EntityExtensions.SaveItem [T](T实体,DbSet1 dbSet, DbContext context, Action
2 foriegnKeyUpdater)中 C:\ TFS \ CGProjects \ GOC \ SCYFIS \ PHTSY \开发\ SRC \数据层\助手\ EntityExtensions.cs:线 27 在Scyfis.Ocyf.DataLayer.Case_PHTSYRepository.Save(Case_PHTSY模型)中 C:\ TFS \ CGProjects \ GOC \ SCYFIS \ PHTSY \开发的\ src \数据层\自定义\ Case_PHTSYRepository.cs:行 44 在Scyfis.Ocyf.Service.Case_PHTSYService.Create(Case_PHTSY模型)中 C:\ TFS \ CGProjects \ GOC \ SCYFIS \ PHTSY \开发的\ src \服务\自定义\ Case_PHTSYService.cs:行 184 InnerException:System.Data.UpdateException 消息=更新条目时发生错误。有关详细信息,请参阅内部异常 来源= System.Data.Entity的 堆栈跟踪: 在System.Data.Mapping.Update.Internal.TableChangeProcessor.CompileCommands(ChangeNode) changeNode,UpdateCompiler编译器) 在System.Data.Mapping.Update.Internal.UpdateTranslator.d_ 0.MoveNext() 在System.Linq.Enumerable.d _711.MoveNext() at System.Data.Mapping.Update.Internal.UpdateCommandOrderer..ctor(IEnumerable
1 命令,UpdateTranslator翻译器) 在System.Data.Mapping.Update.Internal.UpdateTranslator.ProduceCommands() 在System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager) stateManager,IEntityAdapter适配器) 在System.Data.EntityClient.EntityAdapter.Update(IEntityStateManager entityCache) 在System.Data.Objects.ObjectContext.SaveChanges(SaveOptions选项) 在System.Data.Entity.Internal.InternalContext.SaveChanges() InnerException:System.InvalidOperationException Message = ReferentialConstraint中的依赖属性映射到存储生成的列。专栏:'Id'。 来源= System.Data.Entity的 堆栈跟踪: 在System.Data.Mapping.Update.Internal.UpdateCompiler.BuildSetClauses(DbExpressionBinding) target,PropagatorResult row,PropagatorResult originalRow, TableChangeProcessor处理器,布尔insertMode,Dictionary`2&amp; outputIdentifiers,DbExpression&amp;返回,布尔&amp; rowMustBeTouched) 在System.Data.Mapping.Update.Internal.UpdateCompiler.BuildInsertCommand(PropagatorResult) newRow,TableChangeProcessor处理器) 在System.Data.Mapping.Update.Internal.TableChangeProcessor.CompileCommands(ChangeNode) changeNode,UpdateCompiler编译器) 的InnerException:
public partial class Case_PHTSY
{
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public int? FamilyHistoryID { get; set; }
public int? PersonId { get; set; }
public DateTime? ReportDate { get; set; }
public string PhysicianName { get; set; }
public string MRNumber { get; set; }
public virtual F_FamilyHistory F_FamilyHistory { get; set; }
public virtual Person Person { get; set; }
public virtual ICollection<CP_ActualDischarge> CP_ActualDischarges { get; set; }
public virtual ICollection<CP_Barrier> Barriers { get; set; }
public virtual ICollection<CP_AgencyContact> AgencyContacts { get; set; }
public virtual ICollection<CP_DischargeActivity> DischargeActivities { get; set; }
public virtual ICollection<C_Role> Roles { get; set; }
public virtual ICollection<Case_Person_RD1> Case_Person_RD1s { get; set; }
public virtual ICollection<PHTSY_CensusCode> PHTSY_CensusCodes { get; set; }
}
public class CP_ActualDischarge
{
public int Id { get; set; }
[ForeignKey("Case_PHTSY")]
public int Case_PHTSYId{ get; set; }
...
public virtual Case_PHTSY Case_PHTSY { get; set; }
}
public partial class CP_Barrier
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public int? Case_PHTSYId { get; set; }
...
public virtual Case_PHTSY Case_PHTSY { get; set; }
}
public partial class CP_AgencyContact
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public int Case_PHTSYId { get; set; }
...
public virtual Case_PHTSY Case_PHTSY { get; set; }
}
public partial class CP_DischargeActivity
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public int? Case_PHTSYId { get; set; }
...
public virtual Case_PHTSY Case_PHTSY { get; set; }
}
public partial class C_Role
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public int? Case_PHTSYId{ get; set; }
public virtual Case_PHTSY Case_PHTSY { get; set; }
}
}
public partial class Case_Person_RD1
{
public virtual C_Role C_Role { get; set; }
public virtual Case_PHTSY Case_PHTSY { get; set; }
}
外键:
ALTER TABLE [dbo].[CP_ActualDischarge] WITH NOCHECK ADD CONSTRAINT [FK_CP_ActualDischarge_Case_PHTSY] FOREIGN KEY([Case_PHTSYId])
REFERENCES [dbo].[Case_PHTSY] ([Id])
ON DELETE CASCADE
NOT FOR REPLICATION
GO
ALTER TABLE [dbo].[CP_ActualDischarge] CHECK CONSTRAINT [FK_CP_ActualDischarge_Case_PHTSY]
ALTER TABLE [dbo].[CP_AgencyContacts] WITH NOCHECK ADD CONSTRAINT [FK_CP_AgencyContacts_Case_PHTSY] FOREIGN KEY([Case_PHTSYId])
REFERENCES [dbo].[Case_PHTSY] ([Id])
ON DELETE CASCADE
NOT FOR REPLICATION
GO
ALTER TABLE [dbo].[CP_AgencyContacts] CHECK CONSTRAINT [FK_CP_AgencyContacts_Case_PHTSY]
ALTER TABLE [dbo].[CP_Barriers] WITH NOCHECK ADD CONSTRAINT [FK_CP_Barriers_Case_PHTSY] FOREIGN KEY([Case_PHTSYId])
REFERENCES [dbo].[Case_PHTSY] ([Id])
ON DELETE CASCADE
NOT FOR REPLICATION
GO
ALTER TABLE [dbo].[CP_Barriers] CHECK CONSTRAINT [FK_CP_Barriers_Case_PHTSY]
ALTER TABLE [dbo].[CP_DischargeActivities] WITH NOCHECK ADD CONSTRAINT [FK_CP_DischargeActivities_Case_PHTSY] FOREIGN KEY([Case_PHTSYId])
REFERENCES [dbo].[Case_PHTSY] ([Id])
ON DELETE CASCADE
NOT FOR REPLICATION
GO
ALTER TABLE [dbo].[CP_DischargeActivities] CHECK CONSTRAINT [FK_CP_DischargeActivities_Case_PHTSY]
GO
modelBuilder.Entity<Case_PHTSY>().HasMany(c => c.AgencyContacts).WithOptional().HasForeignKey(k => k.Case_PHTSYId);
modelBuilder.Entity<Case_PHTSY>().HasMany(c => c.Barriers).WithOptional().HasForeignKey(k => k.Case_PHTSYId);
modelBuilder.Entity<Case_PHTSY>().HasMany(r => r.DischargeActivities).WithOptional().HasForeignKey(k => k.Case_PhstsyId);
modelBuilder.Entity<Case_PHTSY>().HasMany(c => c.Roles).WithOptional().HasForeignKey(k => k.Case_PHTSYId);
modelBuilder.Entity<Case_PHTSY>().HasMany(m => m.Case_Person_RD1s).WithOptional().HasForeignKey(k => k.Case_PhtsyId);
modelBuilder.Entity<Case_PHTSY>().HasMany(o => o.DischargeActivities).WithOptional().HasForeignKey(k => k.Case_PhstsyId);
modelBuilder.Entity<Case_PHTSY>().HasOptional(o => o.F_FamilyHistory).WithRequired();
modelBuilder.Entity<Case_PHTSY>().HasMany(o => o.PHTSY_CensusCodes).WithOptional().HasForeignKey(k => k.Case_PHTSYId);
the primary table:
CREATE TABLE [dbo].[Case_PHTSY](
[Id] [int] IDENTITY(5000,1) NOT FOR REPLICATION NOT NULL,
[FamilyHistoryID] [int] NULL,
[IntensityNHours] [smallint] NULL,
[IEPRequested] [bit] NULL CONSTRAINT [DF_Case_PHTSY_IEPRequested] DEFAULT (0),
...
[Kidnet] [bit] NULL,
CONSTRAINT [PK_Case_PHTSY] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[Case_PHTSY] WITH NOCHECK ADD CONSTRAINT [FK_Case_PHTSY_F_FamilyHistory] FOREIGN KEY([FamilyHistoryID])
REFERENCES [dbo].[F_FamilyHistory] ([FamilyHistoryID])
ON DELETE CASCADE
NOT FOR REPLICATION
GO
ALTER TABLE [dbo].[Case_PHTSY] CHECK CONSTRAINT [FK_Case_PHTSY_F_FamilyHistory]
GO
ALTER TABLE [dbo].[Case_PHTSY] WITH CHECK ADD CONSTRAINT [FK_Case_PHTSY_Persons] FOREIGN KEY([CaseChildID])
REFERENCES [dbo].[Persons] ([PersonID])
GO
ALTER TABLE [dbo].[Case_PHTSY] CHECK CONSTRAINT [FK_Case_PHTSY_Persons]
CREATE TABLE [dbo].[CP_ActualDischarge](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Case_PHTSYId] [int] NOT NULL,
[DischargeDate] [datetime] NULL,
CONSTRAINT [PK_CP_ActualDischarge] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[CP_ActualDischarge] WITH NOCHECK ADD CONSTRAINT [FK_CP_ActualDischarge_Case_PHTSY] FOREIGN KEY([Case_PHTSYId])
REFERENCES [dbo].[Case_PHTSY] ([Id])
ON DELETE CASCADE
NOT FOR REPLICATION
GO
ALTER TABLE [dbo].[CP_ActualDischarge] CHECK CONSTRAINT [FK_CP_ActualDischarge_Case_PHTSY]
CREATE TABLE [dbo].[CP_AgencyContacts](
[AgencyContactID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
[Case_PHTSYId] [int] NOT NULL,
[AgencyType] [int] NULL,
[Agency] [int] NULL,
CONSTRAINT [PK_Case_PHTSY_AgencyContacts] PRIMARY KEY CLUSTERED
(
[AgencyContactID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[CP_AgencyContacts] WITH NOCHECK ADD CONSTRAINT [FK_CP_AgencyContacts_Case_PHTSY] FOREIGN KEY([Case_PHTSYId])
REFERENCES [dbo].[Case_PHTSY] ([Id])
ON DELETE CASCADE
NOT FOR REPLICATION
GO
ALTER TABLE [dbo].[CP_AgencyContacts] CHECK CONSTRAINT [FK_CP_AgencyContacts_Case_PHTSY]
答案 0 :(得分:2)
它只用了大约一个小时的头撞击,但我使用另一个回复的暗示来解决问题。缺点是EntityFramework对某些关系感到困惑(或者我的描述使用了流利的表达式)。
我终于咬了一口子并清理了数据库中列的一些名称并使它们成为“常规”,即tableName + Id删除了我的流利表达式并且它有效。
我还在一个表上取出了一个复合键,添加了一个Id字段,并使复合键成为唯一索引。
我希望这有助于其他人。
我还确认我怀疑在使用SQL Server 2008时不需要标识注释。正在使用的数据库是2005年。
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
答案 1 :(得分:2)
我有同样的错误。最终追溯到一个不正确的关系。我在数据库中的两个主键之间进行链接,而不是主要和外来。
答案 2 :(得分:0)
我不得不手动删除.edmx中的错误引用。