问题
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.
回答1:
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();
回答2:
Check Student entity pid property in EDM: storegeneratedPatteren = None. Quite confused.
Still has to do with the identity specification (is identity, identity increment, identity seed) for the table you are adding to, or the table column a relationship was mapped to. The error 'A dependent property in a ReferentialConstraint is mapped to a store-generated column' shows if:
You pass a new object to addObject() with a field for which a value was set that should be generated by the database. Solution: Do not pass a value for fields that have an autoincrement id in the database.
You accidentally mapped the primary key of a table to a wrong foreign column in your database. Solution: Review the foreign key relationship.
The second case is less obvious, but it happens often if you quickly drag and drop constraints in a diagram.
来源:https://stackoverflow.com/questions/4035834/cant-insert-data-to-with-ef-with-master-detail-relationship