无法使用具有Master-detail关系的EF插入数据 [英] Can't insert data to with EF with Master-detail relationship
问题描述
假设我有2个表:
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.
然后使用EF生成实体模型。因此尝试使用以下代码插入新数据:
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();
然后我收到错误:
参考代码中的依赖属性映射到一个商店生成列。列:'pid'。
Then I get error as: A dependent property in a ReferentialConstraint is mapped to a store-generated column. Column: 'pid'.
如何解决?
修改代码如下:
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();
然后我可以插入人,但对于学生,仍然会收到相同的错误。在EDM中检查学生实体pid属性:storegeneratedPatteren = None。很混乱
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.
推荐答案
听起来像你有一个学生是一种人。如果这是真的,那么您应该考虑使用每种类型的继承 。这里的详细信息 http://msdn.microsoft.com/en-us/library/bb738685 .aspx
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
已编辑:
如果您选择不使用继承,则需要先插入该人:
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();
这篇关于无法使用具有Master-detail关系的EF插入数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!