2011-09-30 113 views
6

我第一次使用实体框架,我试图用集合创建一个对象(并且我想要创建集合中的所有对象在数据库中),但我有一些外键违规。实体框架一对多插入 - 违反外键

我的示例表:

table APPOINTMENTS: ID, VAR1, DATE_APPOINTMENT 
table GUESTS: ID, APPOINTMENT_ID, USER_ID, VAR2, VAR3 

我的测试代码:

DomainService aux = new DomainService(); 

APPOINTMENTS appointment = new APPOINTMENTS(); 
appointment.VAR1 = "BLA"; 
appointment.DATE_APPOINTMENT = new DateTime(); 

//The user with id = 1 is already created in the database 
appointment.GUESTS.Add(new GUESTS { USER_ID = 1, VAR2 = 1, VAR3 = "F" }); 

aux.InsertAppointment(appointment); 

在我的DomainService有:

public void InsertAppointment(APPOINTMENTS appointment) 
{ 
    using (var context = this.ObjectContext) 
    { 
     context.AddToAPPOINTMENTS(appointment); 
     context.SaveChanges(); 
    } 
} 

但我发现了这个错误: {“ORA -02291:违反了完整性约束(FK_GUESTS_APPOINTMENTS) - 未找到父键“}

我在做什么错?

UPDATE: 要创建在数据库中的ID,我使用的每个表中序列和插入前触发器来获取下一个值。 当我创建单个对象时,例如没有客人的约会,它会插入到数据库中,并生成ID。

+0

我有整整做在EF中也是这样,它适用于我。两个表中的主键都是自动编号。我正在使用sql server的数据存储 –

+0

我在插入前使用序列和触发器...当我尝试创建一个没有guest的约会时,它会生成一个ID,当我尝试使用现有的约会ID创建一个guest时,它也能正常工作 – Canastro

+0

@MuhammadAdeelZahid他使用的是Oracle,而不是SQL Server –

回答

4

的解决了这个问题:

"The ID fields that are generated from sequences won't be handled correctly. After saving the entities the ID's will be returned as 0. I'll fix this by manually hacking the SSDL (open your .edmx file in a text editor) with StoreGeneratedPattern="Identity" attributes on the ID fields (lines 6 and 16). Note that designer may rip that change out upon future modification.

While I suppose it's not absolutely necessary it might also be prudent to modify some type metadata such as changing "number"s to "int"s in your SSDL and "Decimal"s to "Int32"s in your CSDL where applicable. Frequently these don't auto-generate with the desired values especially with XE."

@http://www.chrisumbel.com/article/oracle_entity_framework_ef

+0

<的EntityType名称= “窗口小部件”> <属性名= “为widgetid” StoreGeneratedPattern = “同一性” 类型= “数字” 可为空= “假”精度=“8”/> –

0

我不知道你在哪里设置你的主键(约会类的ID属性)。你在数据库端使用密钥生成器吗?如果不是这应该是问题。

+0

我正在使用序列在插入前获取下一个值的触发器。 – Canastro

-1

您插入的记录中的外键值在约束返回的父表中找不到。

+1

那么,是不是要实体框架插入约会和客户与正确的APPOINTMENT_ID FK? – Canastro

+0

我不是一个java程序员,所以我不知道你的实体框架做了什么或不做什么。如果框架应该首先插入父项,那么是否有可能有更多的设置可以为您的对象执行?查看你的代码,如果我正确地阅读它,你在APPOINTMENT之前创建了GUEST,而GUEST.APPOINTMENT_ID是外键返回到APPOINTMENT.APPOINTMENT_ID。在创建GUEST对象时,是否在APPOINTMENT_ID = 1的APPOINTMENT表中有记录? –

+0

发现了这个问题。这是一个映射问题...您需要对生成的映射进行一些更改才能做到这一点。 EF不喜欢的Oracle的xD – Canastro

1

对于我来说,这个问题是通过打开图的.edmx根本解决,将每个主键中的属性StoreGeneratedPattern从None更改为Identity。保存一切后都很好。

我使用VS 2012,实体框架5(6尚不支持),甲骨文11.2,去年12 ODP.NET,.NET 4.5

1

在EF代码第一种方法的情况下,如果这个错误来

(ORA-02291: integrity constraint (FK_GUESTS_APPOINTMENTS) violated - parent key not found)

在我的情况下有两个表有标识列。于是我就加入

[DatabaseGenerated(DatabaseGeneratedOption.Identity)] 

属性略高于列我的模型类,这是在数据库中标识列,它解决了我的问题:)

希望这有助于:)