简体   繁体   English

实体框架在知道父项的情况下插入子项记录

[英]Entity Framework Inserting child record with parent knowing

I have this problem where I am inserting a child record and in the database the navigation column is null instead of referencing the parents Id . 我在插入子记录时出现此问题,并且在数据库中导航列为null而不是引用父Id

How can I fix this? 我怎样才能解决这个问题?

There will only ever be 1 record in the AdminConfiguration Table AdminConfiguration表中将永远只有1条记录

Model 模型

public class AdminConfiguration : Entity
{
    public virtual List<ApplicationConfiguration> ApplicationConfiguration { get; set; }
}

Child 儿童

public class ApplicationConfiguration : Entity
{
    public Applications Application { get; set; }
    public string ApiKey { get; set; }
    public string IpAddress { get; set; }
    public int Port { get; set; }
    public string HttpScheme { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
}

Insert code 插入代码

public ApplicationConfiguration Insert(ApplicationConfiguration entity)
{
    Db.ApplicationConfiguration.Add(entity);
    Db.SaveChanges();
    return entity;
}

What the DB looks like after insert: 插入后数据库的外观如下:

ID | Other columns | AdminConfiguration_Id
1  | Other values  | NULL

You need an appropriate navigation property on your ApplicationConfiguration entity so EF can map the relationship, personally I would also create a foreign key property as below, as it often easier to just specify the related entity ID rather than having to populate the navigation property. 您在ApplicationConfiguration实体上需要一个适当的导航属性,以便EF可以映射关系,就我个人而言,我还将创建一个如下所示的外键属性,因为通常只需指定相关的实体ID而不是必须填充导航属性即可。

public class ApplicationConfiguration : Entity
{
    public Applications Application { get; set; }
    public string ApiKey { get; set; }
    public string IpAddress { get; set; }
    public int Port { get; set; }
    public string HttpScheme { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    public virtual AdminConfiguration AdminConfiguration { get; set; }
    [ForeignKey("AdminConfiguration")]
    public int AdminConfigurationId { get; set; }
}

This will get rid of the AdminConfiguration_Id column and instead create a AdminConfigurationId columns that will map to the property on your class. 这将摆脱AdminConfiguration_Id列,而是创建一个AdminConfigurationId列,该列将映射到您的类的属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM