微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我有一个现有的数据库,其中有两个表MailServers和MailDomains. MailDomains的外键列MailServerId指向MailServers中的Id主键列.所以我们在这里有一对多关系.

我跟着this article,并通过实体数据模型向导中的“数据库中的第一个代码”模型创建了我的实体框架POCO.这产生了以下两个C#类:

public partial class MailServer
{
    public MailServer()
    {
        MailDomains = new HashSet<MailDomain>();
    }

    public int Id { get; set; }

    public virtual ICollection<MailDomain> MailDomains { get; set; }
}



public partial class MailDomain
{
    public MailDomain()
    {
    }

    public int Id { get; set; }

    public string DomainName { get; set; }

    public int MailServerId { get; set; }
    public virtual MailServer MailServer { get; set; }
}

现在我的问题是在创建和将新对象添加数据库中的以下两种方法之间是否存在差异.

方法(A):将新孩子添加到父列表中:

var mailServer = new MailServer();
        var mailDomain = new MailDomain() {
            DomainName = "foobar.net",};
        mailServer.MailDomains.Add(mailDomain);

        using(var context = new MyContext){
            context.MailServers.Add(mailServer);
            context.SaveChanges();
        }

方法(B):将孩子的导航属性设置为父母:

var mailServer = new MailServer();
        var mailDomain = new MailDomain() {
            DomainName = "foobar.net",MailServer = mailServer,};

        using(var context = new MyContext){
            context.MailDomains.Add(mailDomain);
            context.SaveChanges();
        }

我还假设在方法(A)中,新的MailDomain实例被自动添加到集合上下文.MailDomains在方法(B)中,新的MailServer实例被自动添加到集合context.MailServers.这是正确的还是我必须手动这样做?

所以再问一次,我的问题是:这两种方法是否可互换?
它只是混淆我在数据库中只有一个属性/列设置(即MailDomains中的外键),而在C#代码中有两个属性(每个类中一个)可以修改.

解决方法

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

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

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关系等).

如果你的意思是:在保存之前,实体可以通过上下文获得,我不这么认为(我不是100%肯定的).

原文地址:https://www.jb51.cc/csharp/96456.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐