且构网

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

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

更新时间:2023-12-01 17:50:52

是的,这两种方法是可以互换的.这使您可以从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).