Home > Software design >  .NET 6 - EF : how do I insert one to many relation ship with null reference?
.NET 6 - EF : how do I insert one to many relation ship with null reference?

Time:07-25

I have a one-to-many relationship with Author and Books. What I want to do is insert authors, but I don't know what books they released yet, so the books are empty for now.

I've tried different logic and relationship connection between author and books but still get:

Object reference not set to an instance of an object.

My code:

public class Author
{
    public Guid Id { get; set; }
    public string name { get; set; }
    public ICollection<Book>? Book { get; set; } = new List<Book>();
}

public class Books
{
    public Guid Id { get; set; }
    public int Page { get; set; }
    public string? Name { get; set; }
    public Author? Author{ get; set; }
    public Guid AuthorId { get; set; }
}

Relationship connection between Author and Books

modelBuilder.Entity<Author>()
            .HasMany(u => u.Book)
            .WithOne(a => a.Author)
            .HasForeignKey(aa => aa.AuthorId)
            .OnDelete(DeleteBehavior.Cascade);

Attempt at inserting data into Author with no books yet:

_context.Author.Add(request.Author);

CodePudding user response:

Check this out Working example

  • Related