[英]EntityFramework is inserting a new register instead set the id for relationship
I'm developing a website that allows the users Post issues. 我正在开发一个允许用户发布问题的网站。
I have 3 tables: 我有3张桌子:
When I save the Post the system inserts a new Post, do the relationship between PostService and Post (by the PostId), but, it should set the CityId in to PostService, but, instead, it creates a new City, and do the relationship to the PostService. 当我保存Post时,系统会插入一个新Post,执行PostService和Post之间的关系(通过PostId),但是,应将CityId设置为PostService,而是创建一个新的City,并建立关系到PostService。
Here, we set the selected City into the PostService: 在这里,我们将选定的城市设置为PostService:
orcamento.Cidades = db.Cidades.Where(c => c.CidNome.Trim().ToLower() == orcamento.Cidades.CidNome.Trim().ToLower()).FirstOrDefault();
and here, we persist the Post: 在这里,我们坚持发表:
Post post = new Post();
post.PosData = DateTime.Now;
post.Usuarios = db.Usuarios.Where(u => u.UsuEmail == User.Identity.Name).FirstOrDefault();
post.PostOrcamentoServico.Add(orcamento);
db.Post.Add(post);
db.SaveChanges();
Why it is creating a new City instead set the CityID to PostService? 为什么要创建一个新城市而不是将CityID设置为PostService?
To fix that, use the same Transaction of the Context. 要解决此问题,请使用上下文的同一事务。
The following code were in another Context 以下代码在另一个上下文中
orcamento.Cidades = db.Cidades.Where(c => c.CidNome.Trim().ToLower() == orcamento.Cidades.CidNome.Trim().ToLower()).FirstOrDefault();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.