且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

实体框架 6:将子对象添加到父列表与将子对象的导航属性设置为父对象

更新时间:2023-12-01 17:46:34

是的,这两种方法是可以互换的.这允许您从 MailServer 或 MailDomain 的角度创建对象图并将其保存到数据库.

Yes, the two approaches are interchangeable. This allows you to create and save your object graph to the database from either the perspective of the MailServer or the MailDomain.

如果您执行代码优先,则可以选择删除不需要的属性和映射.

If you do code-first, you have the option of removing the properties and mappings if they're not needed.

我还假设在方法 (A) 中,新的 MailDomain 实例是在方法 (B) 中自动添加到 context.MailDomains新的 MailServer 实例会自动添加到 context.MailServers.这是正确的还是我必须手动执行?

I also assume that in approach (A) the new MailDomain instance is automatically added to context.MailDomains while in approach (B) the new MailServer instance is automatically added to context.MailServers. Is that correct or do I have to do that manually?

这取决于您所说的添加到上下文中"是什么意思.如果你的意思是:当你持久化时它是否会自动保存到数据库中,答案是肯定的.使用像 EF 这样的 ORM 的一大好处是它可以自动处理保存完整的对象图(以及同步 PK/FK 关系等).

It depends what you mean by "added to the context". If you mean: does it automatically get saved to the database when you persist, the answer is yes. One of the big benefits to using an ORM like EF is that it handles saving a full object graph automatically (and syncing PK/FK relations, etc.).

如果您的意思是:实体在保存之前是否可以通过上下文访问,我不这么认为(我不是 100% 确定).

If you mean: will the entity be available via the context before saving, I don't think so (I'm not 100% sure).