views:

26

answers:

1

Suppose I have 2 tables:

Person(pid, ....)   //Pid is identify colum as primary key
Student(pid, Student_No,...)   //pid is foreign key from Person, pid is a primary key too.

Then use EF to generate entity model. THen try to insert new data with following code:

 Person person = new Person()
           { FirstName = "FirstName", LastName= "LastName", ... };
 Student student = new Student(){Student_No="001", ...};
 Student.Person = person;
 mycontext.Students.AddObject(student);
 mycontext.SaveChanges();

Then I get error as: A dependent property in a ReferentialConstraint is mapped to a store-generated column. Column: 'pid'.

How to fix it?

Modify the code like:

 Person person = new Person(){ FirstName = "FirstName", LastName= "LastName", ... };
  mycontext.People.AddObject(person);
  mycontext.SaveChanges();

 Student student = new Student(){Student_No="001", Person = person,  ...};
 // or  Student student = new Student(){Student_No="001", pid= person.pid,  ...};
 mycontext.Students.AddObject(student);
 mycontext.SaveChanges();

then I was able to insert for person, but for Student, still get same error. Check Student entity pid property in EDM: storegeneratedPatteren = None. Quite confused.

A: 

Sounds like you have a student which is a type of person. If this is true then you should consider using Table-per-type Inheritance. Details here http://msdn.microsoft.com/en-us/library/bb738685.aspx


Edited:

If you choose not to use inheritance you need to insert the person first:

 Person person = new Person()
           { FirstName = "FirstName", LastName= "LastName", ... };

 mycontext.Person.AddObject(person);
 mycontext.SaveChanges();
John Hartsock
Even I attach person, I still get same error. In Student table, pid is primary key and foreign key. Not sure if is it because of this.
KentZhou
@KentZhou ...Sorry, I didnt understand that Student Table was a 1 to 1 relationship. Are you using Table per type inheritance?
John Hartsock
I did not use any inheritance becuase there are some duplicate column names in both tables,. Just following the default EF and create two entities in EDM. If not creaet key on pid in student table, this table will has no key and can be modeled by EF or Readonly.
KentZhou
Then you need to insert the person first
John Hartsock
Thanks for help. I tried as you suggested, but still get same error on student.
KentZhou
did you save after person?
John Hartsock
Finally, resove this problem. Just entity from edm and added again. If only update model from database, it won't work. Looks like EF can't update model to reflect the changes in database correctly.
KentZhou