问题描述
类似的情况:http://stackoverflow.com/questions/630320/how-to-add-several-dependent-records-with-linq2sql
(这似乎符合逻辑,但它不为我工作)
Similar situation to : http://stackoverflow.com/questions/630320/how-to-add-several-dependent-records-with-linq2sql(this seems logical, but it doesn't work for me)
ASP.NET MVC + LINQ2SQL
ASP.NET MVC + Linq2SQL
我有2表称为挑战和参与者。
I have 2 tables called Challenges and Participants.
- 挑战{challengeId,
ChallengeDesc,applicantId,
respondantId} - {参与者participantId,名字,姓氏}
有参与者和挑战之间一对多的关系 - 每个键(applicantId,RespondantId)1
There are 1-many relationships between participants and Challenges - 1 for each key (applicantId, RespondantId).
我有收集所有领域创造新的申请人和respondant和挑战的输入形式。使用DataBinder绑定所有领域的挑战,这是孩子的参与者正确,但是,参与者对象的名字没有在挑战对象浏览由LINQ2SQL创建结构时,匹配的键名(applicantId和参与者对象相匹配,并respondantId与PARTICIPANT1匹配对象)。
I have an input form that collects all fields to create a new applicant and respondant and the challenge. The Databinder binds all the fields to Challenge and it's child participants correctly, however, the participant objects' names don't match the key names in the challenge object when browsing the structure created by Linq2Sql (applicantId matches with Participant object and respondantId matches with Participant1 object).
所以,当我尝试的SubmitChanges()InsertOnSubmit(aChallenge)后,我得到一个foreign_key约束验证消息从LINQ2SQL回来。在SQL Server Profiler中,我可以看到,参与者正在正确地创建,但被保存的挑战时,这些新插入的参与者的ID没有被这样的系统是扔一个外键冲突的消息设置为挑战对象。
So when i try to SubmitChanges() after InsertOnSubmit(aChallenge) i get a foreign_key constraint validation message back from Linq2Sql. In SQL Server Profiler, I can see that the participants are being created properly, but when the challenge is being saved, the IDs of these newly inserted participants are not being set to the challenge object so the system is throwing a foreign key violation message.
我如何突破这个?
推荐答案
您必须这样说,我认为写的(假设你有类参与者与挑战):
You have to write it this way I think (assuming you have classes Participant and Challenge):
Participant applicant = new Participant();
Participant respondant = new Participant();
//update your participants here
Challenge insertedChallenge = new Challenge();
//update your challenge values here
applicant.Challenges.add(insertedChallenge);
respondant.Challenges1.add(insertedChallenge);
submitChanges();
LINQ到SQL应该自动分配这些属性(质疑和挑战),因此它可以为您设置键值。
Linq-to-SQL should automatically assign these properties (Challenges and Challenges) so it can set the key values for you.
希望它帮助。
这篇关于LINQ2SQL插入记录的表数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!