[英]EF6 Update Foreign Key after insert Data from another Form
I'm trying to update a table's foreign key after I insert record from a different form. 从其他表格插入记录后,我试图更新表的外键。
Table Project : 表项目 :
ProjectID CommentID
Table Comments : 表注释 :
CommentID Date Comment
First, I create the Project
and assign CommentID
a NULL
value since there is no comment yet. 首先,我创建
Project
并为CommentID
分配一个NULL
值,因为还没有评论。 So far so good. 到现在为止还挺好。
Then, in some moment, I need to add a comment to my project. 然后,稍后,我需要在项目中添加评论。 I can successfully add comments, but can't assign
CommentID
in related Project
table. 我可以成功添加注释,但是不能在相关的
Project
表中分配CommentID
。
This is how I'm trying to do (with no success): 这就是我试图做的(没有成功):
MyEntities ctx = new MyEntities();
tblComents coment = new tblComments()
{
Date = DateComent.Value,
Comment = TxtComment.Text.Trim()
};
ctx.tblComments.Add(comment);
var projet = new tblProject { tblComments = comment };
ctx.SaveChanges();
Like this, I create the comment but the foreign key is never assigned in table Projects
. 这样,我创建了注释,但是从未在表
Projects
分配外键。
Any help? 有什么帮助吗?
Thanks 谢谢
You are adding the comment to a new
project that has nothing to do with your database: 您正在将注释添加到与数据库无关的
new
项目中:
tblComents coment = new tblComents()
{
Date = DateComent.Value,
Coment = TxtComent.Text.Trim()
};
tblProject project = ctx.tblProject(x=> x.Id == someid); // find the project you want
if(project != null) project.tblComents.Add(coment);
ctx.SaveChanges();
You should either get a project from your database (code above) and then add the comment to that project, or add the project to database not the comment(code below): 您应该从数据库中获取一个项目(上面的代码),然后将注释添加到该项目,或者将项目而不是注释中的项目添加到数据库(下面的代码):
tblComents coment = new tblComents()
{
Date = DateComent.Value,
Coment = TxtComent.Text.Trim()
};
tblProject project = new tblProject();
ctx.tblProjects.Add(project);
if(project != null) project.tblComents.Add(coment);
ctx.SaveChanges();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.