何时使用DbSet< T>。新增()VS DbSet< T> .Attach()

编程入门 行业动态 更新时间:2024-10-16 19:19:48
本文介绍了何时使用DbSet< T>。新增()VS DbSet< T> .Attach()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我一直使用添加(),跑进其中,由母公司正在复制数据库的时候添加问题 ING一个孩子。使用附加()解决了这个,但我想知道为什么,而不是盲目地跌跌撞撞各地。

I have been using Add() and ran into a problem where by a parent entity was being duplicated in the database when Adding a child. Using Attach() solved this but I would like to know why rather than blindly stumbling around.

推荐答案

那么,当你使用连接你告诉该实体是已经在数据库的背景下,的SaveChanges 将拥有附加的实体没有影响。 添加,在另一方面,改变了实体的状态在上下文(如果它已经存在)为添加 ,这意味着它将总是插入的实体,当你调用数据库的SaveChanges 。

Well, when you use Attach you tell the context that the entity is already in the database, SaveChanges will have no effect over attached entities. Add, on the other hand, changes the state of the entity in the context (if it's already there) to Added, meaning it will always insert the entity in the database when you call SaveChanges.

这就是区别。

更多推荐

何时使用DbSet< T>。新增()VS DbSet< T> .Attach()

本文发布于:2023-11-02 16:58:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1552925.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:LT   DbSet   Attach   GT

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!