IDbSet.Add和DbEntityEntry.State = EntityState.Added有什么区别? [英] What is the difference between IDbSet.Add and DbEntityEntry.State = EntityState.Added?

查看:351
本文介绍了IDbSet.Add和DbEntityEntry.State = EntityState.Added有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在EF 4.1+中,这两行代码之间有区别吗?

dbContext.SomeEntitySet.Add(entityInstance);
dbContext.Entry(entityInstance).State = EntityState.Added;

还是他们做同样的事情?我想知道一个因素对子集合/导航属性的影响是否与另一个因素不同.

解决方案

使用dbContext.SomeEntitySet.Add(entityInstance);时,此状态及其所有相关实体/集合的状态都设置为添加",而dbContext.Entry(entityInstance).State = EntityState.Added;还会添加所有相关实体/收集到上下文,但将其保留为未修改状态. 因此,如果您要创建的实体具有相关实体(其值不为null),则在使用添加"时,它将为该子实体创建一个新对象,而使用其他方法则不会.

In EF 4.1+, is there a difference between these 2 lines of code?

dbContext.SomeEntitySet.Add(entityInstance);
dbContext.Entry(entityInstance).State = EntityState.Added;

Or do they do the same thing? I'm wondering if one might affect child collections / navigation properties differently than the other.

解决方案

When you use dbContext.SomeEntitySet.Add(entityInstance); the status for this and all its related entities/collections is set to added, while dbContext.Entry(entityInstance).State = EntityState.Added; adds also all the related entities/collections to the context but leaves them as unmodified. So if the entity that you are trying to create has a related entity (and it's value its not null), when you use Add it will create a new object for that child entity, while with the other way it won't.

这篇关于IDbSet.Add和DbEntityEntry.State = EntityState.Added有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆