【问题标题】:EF Core : how to add items into Navigation Property with one-to-many relationship?EF Core:如何将项目添加到具有一对多关系的导航属性中?
【发布时间】:2022-10-19 10:57:17
【问题描述】:

我正在尝试将内容添加到导航属性中。

我想建立一个允许用户将记录输入数据库的系统。一个记录至少有一个或多个许可证。因此,它具有一对多的关系。

我试图通过许可证输入一项工作性质,但出现此错误:

你调用的对象是空的

如何将 Permit 类中的项目传递给 Record 类?

课程

[Table("record" , Schema = "public")]
public class Record
{
    [Key]
    public string Serial_Num {get; set;}
    public string job_nature {get; set;}
    //navigation property
    public ICollection<Permit> permits {get; set;}
}

[Table("permit" , Schema = "public")]
public class Permit
{
    [Key]
    public int id {get; set;}
    public string Serial_Num {get; set;}
    public string permit {get; set;}
    //navigation property
    [Required]
    public Record Record {get; set;}
}

模型构建器

modelBuilder.Entity<Record>()
                .HasMany(p => p.permits)
                .WithOne(r => r.Record)
                .HasForeignKey(p => p.Serial_Num)
                .OnDelete(DeleteBehavior.Cascade);

部分代码(1对1关系试用)

// Record Class
Record objRecord = new Record();
objRecord.Serial_Num = "001";
objRecord.job_nature = "test";

// Permit Class
Permit objPermit = new Permit();
objPermit.Serial_Num = objRecord.Serial_Num;
objPermit.permit = "permit_test";

// I'm trying to include Permit into Record, but returns 'Object reference not set to an instance of an object' error.
objRecord.permits.Add(objPermit);
context.record.Add(objRecord);
context.SaveChanges();

【问题讨论】:

    标签: c# entity-framework-core blazor-server-side


    【解决方案1】:
    [Table("record" , Schema = "public")]
    public class Record
    {
        // Add the constructor to initialize permits
        public Record()
        {
            permits = new HashSet<Permit>();
        }
        
        [Key]
        public string Serial_Num {get; set;}
        public string job_nature {get; set;}
        //navigation property
        public ICollection<Permit> permits {get; set;}
    }
    

    【讨论】:

    • 哇,它有效!基本上这些接口是空的,我不能用它做任何事情。
    【解决方案2】:

    这个怎么样:

    objRecord.permits = new List<Permit>()
    

    然后添加到列表中。

    【讨论】:

    • 因为 objRecord.permits 为空,所以会有同样的错误。解决此错误后,我将其更改为 List<> 。
    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center。
    猜你喜欢
    • 1970-01-01
    • 2019-08-06
    • 2021-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多