How to insert data for composite object? - entity-framework-4

Suppose I have table Person, student:
Person(id, ....): id is primary key and identity column.
Student(id, .....): id is primary key and foreign key connect to person->ID
In ria service meta data, set Student as composite of Person:
[Include]
[Composition]
public Student Student { get; set; }
then I want to insert a new student data. what I did is something like:
Person p = new person(){....};
p.Student = new Student{....};
_context.People.AddObject(p);
_context.SaveChanges();
then I got error:
System.Data.UpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SqlClient.SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Student_Person". The conflict occurred in database "MyDB", table "dbo.Person", column 'id'.
The statement has been terminated.
How to fix this problem?

Related

Change foreign key type without losing data.(asp.net)

I have created one to many relationship between student and department tables using entity framework.But unfortunately in the student table the foreign key (DepartmentId) type I gave string but it should be int.How can i resolve this issue without losing data????????
N.B: I am using entity framework code first approach.
I think you cannot do that, considering that your DepartamentID is the PK of the table Departament, so you have to drop the old field and create a new one, something like this
AddColumn("dbo.Departament", "DepartamentID2", c => c.Int(nullable: false));
Sql(#"
UPDATE dbp.Departament
SET DepartamentID2 = DepartamentID
");
Sql(#"
ALTER TABLE dbo.Departament drop CONSTRAINT <The FK Constraint>
");
DropColumn("dbo.Departament", "DepartamentID");
RenameColumn("dbo.Departament", "DepartamentID2", "DepartamentID");
Sql(#"
ALTER TABLE dbo.Departament add PRIMARY KEY (DepartamentID)
");
Sql(#"
ALTER TABLE dbo.Departament add CONSTRAINT <The FK
constraint>
");

Cannot delete User in GORM

I'm getting this error when I'm trying to delete a Interviewee in the GORM :
Referential integrity constraint violation: "FK_APCC8LXK2XNUG8377FATVBN04:
PUBLIC.USER_ROLE FOREIGN KEY(USER_ID) REFERENCES PUBLIC.USERS(ID) (40)";
SQL statement: delete from users where id=? and version=? [23503-176]
And this is my domain :
package com.cgi.recruitmenttest
import com.cgi.security.User
class Interviewee extends User{
String firstName
String lastName
String email
String telephone
String level
static hasMany = [results:Result,tests:TestInterviewe]
static constraints = {
lastName()
firstName()
email(email: true)
telephone(nullable: true)
level inList: ['Debutant', 'Confirme', 'Expert']
}
}
I just try to create a interviewee without results and tests but when I delete, i get this error..
Can someone help ? Thanks
You want to delete a data from USERS table but in USER_ROLE table it contained a foreign key (named USER_ID) of USERS table. That's why you are unable to delete. Delete USER_ROLE table's data first according USERS table ID then you may able to delete.

EF Code First Modelbuilder creating unique identifiers where it should not

I have something like this:
modelBuilder.Entity<TransactionHistory>()
.HasOptional(history => history.Sender)
.WithMany()
.Map(s => s.MapKey("Sender"))
.WillCascadeOnDelete(false);
modelBuilder.Entity<TransactionHistory>()
.HasOptional(history => history.Receiver)
.WithMany()
.Map(s => s.MapKey("Receiver"))
.WillCascadeOnDelete(false);
And in my table TransactionHistory, it creates unique identifiers at columns Sender and Receiver. I don't want those columns to be unique, what do i do?
TransactionHistory model:
public class TransactionHistory
{
public Account Sender { get; set; }
public Account Receiver { get; set; }
}
Edit: Ok. Apparently uniqueidentifiers are not the case. The problem is, that when i am adding transactionhistory item into database, i got the following error:
Violation of PRIMARY KEY constraint 'PK_dbo.Accounts'. Cannot insert
duplicate key in object 'dbo.Accounts'.\r\nThe statement has been
terminated.
An i add this item like that:
context.Transactions.Add(history);
context.savechanges();
(Transactions is a transactionhistory object)
EF uses uniqueidentifier as SQL column type for the foreign keys because the principal's (= Accounts) primary key is a uniqueidentifier - in C# it is a Guid, like public Guid AccountId { get; set; }.
It must choose this type because principal and dependent key types must match in a foreign key relationship in the database.
This does not mean that the foreign key column is unique (or has a unique index). Of course you can use the same uniqueidentifier value multiple times as the foreign key column value.
Entity framework works by storing a cache of a bunch of objects in DBContext. Even if all the properties are the same on your Account object (including your pk) entity framework will see this as a new object unless you remind it "hey, you already know about this". I can think of 2 ways to do this:
context.Entry(history.Sender).State = EntityState.Modified;
context.Entry(history.Receiver).State = EntityState.Modified;
or
Make sure when you set the Accounts on your history object that they are already attached to your dbcontext.
var sender = context.Accounts.FirstOfDefault(...your condition here...);
var receiver = context.Accounts.FirstOfDefault(...your condition here...);
history.Sender = sender;
history.Receiver = receiver;
Also EF does not load navigation/related entities unless you tell it to. So if you are editing history make sure you using .Include() to pull in your related objects.
Hope that helps.

3,Mapping column named 'interface' in Grails seems impossible

It seems that it is impossible with Grails to map a domain class to a database table that has is a foreign key column named 'interface'.
In my case there's a relationship with two tables INTERFACE and INTERFACE_DETAILS. They are legacy databases and column names can not be changed or added.
Put it simple INTERFACE_DETAILS has an FK column 'INTERFACE' referring to PK INTERFACE.ID
class Interface {
String id;
static mapping = {
table "INTERFACE"
version false
id generator: 'assigned'
id column: 'id', sqlType:"varchar2(20)"
}
class InterfaceDetails {
Interface iface;
static belongsTo = [iface: Interface]
static mapping = {
table "INTERFACE_DETAILS"
version false
id column: 'interface'
iface column: 'INTERFACE', sqlType:"varchar2(20)", insertable: false, updateable: false
}
}
I'm currently using H2 database. When I try to add a row to InterfaceDetails this error occurs:
Referential integrity constraint violation: "FK351396597E3917F9: PUBLIC.INTERFACE_DETAILS FOREIGN KEY(INTERFACE) REFERENCES PUBLIC.INTERFACE(ID)"; SQL statement:
insert into INTERFACE_DETAILS (interface) values (null) [23506-164]
I wonder why hibernate adds null for 'interface' value ?
I do have to have line : "id column: 'interface'" because in other case Hibernate will generate an extra column: "iface_id" and this is not suitable. Existing database columns can not be changed.
This is quite puzzling. Please tell me that Grails can handle this situation.
stripped down schema:
create table interface (id varchar2(20) not null,primary key (id));
create table interface_details (interface varchar2(20) not null, name varchar(255) not null, primary key (interface));
alter table interface_details add constraint FK_INTERFACE foreign key (interface) references interface;

GORM 1-to-many relationship -- 3 tables created rather than 2

All
My problem is I'm creating a 1-to-many relationship in GORM and expect 2 database tables to be created as backing objects. 3 are created which makes SQL queries overly complex.
I've created a close variant on the 1-to-many in the GORM documentation:
class Status {
List errorMessage
static hasMany = [errorMessage:ErrorMessage]
}
and the error message class:
class ErrorMessage {
String message
static belongsTo = Status
}
I expected this to create two database tables:
CREATE TABLE status {
ID NUMBER(19,0),
VERSION NUMBER(19,0),
//other fields
}
CREATE TABLE error_message {
ID NUMBER(19,0),
VERSION NUMBER(19,0),
STATUS_ID NUMBER(19,0),
MESSAGE VARCHAR(255)
//other fields
}
but actually it wants a third table,
CREATE TABLE status_text {
status_text_id NUMBER(19,0),
text_idx NUMBER(19,0),
text_id NUMBER(19,0)
}
Adding Status to the ErrorMessage (a hack as I don't want ErrorMessage to have a reference to Status) class removes the third table but keeps the second foreign key resulting in the Text child object having two foreign key fields.
What I want is simple - just a set of objects attached to the parent will be deleted when it is - any thoughts what I'm doing wrong?
Thanks
I don't think you can satisfy both requirements, i.e. that you have cascading deletes and no join table. You need the belongsTo to get cascading deletes and that makes the relationship bidirectional. To remove the join table, name the belongsTo with the Map syntax:
class ErrorMessage {
String message
static belongsTo = [status: Status]
}

Resources