Mathis Hüttl
Mathis Hüttl

Reputation: 93

Entity Framework - Related row gets duplicated without any reason

I have a "AddBookForm" that gets an Author as parameter. When the form opens I enter a Book-Title and then the book should be saved with the Author as relation. The Problem is, that when I save the book I can find in the database a new author entry too and the book gets related to the new one.

As Example: I have the Author with the ID 6 and Name "Franz Kafka" and give this Author-Object as parameter to my AddBookForm. I enter a title and hit "save" then in the Database I can find a new Author with the consecutive number 7 with the same Name and the Book I just added is related to ID 7 instead of 6.

class Book
{
    public int Id { get; set; }
    public Author Author { get; set; }
    public string Title { get; set; }
}

using (AddBookForm frm = new AddBookForm(author))
{
    frm.ShowDialog();
}

public partial class AddBookForm: Form
{
    Author author;

    public AddBookForm(Author author)
    {
        InitializeComponent();
        this.author = author;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        using (MyDbContext db = new MyDbContext())
        {
            Book book = new Book();
            book.Title = textBox1.Text;
            book.Author = this.author;

            db.Books.Add(book);
            db.SaveChanges();

            this.Close();
        }
    }
}

Upvotes: 0

Views: 83

Answers (1)

Neil
Neil

Reputation: 11919

All the properties from the database should come from the same DbContext. Your Author property comes from a different DbContext to the one in the button click, so EF will automatically create a new one.

Try this:

using (MyDbContext db = new MyDbContext())
{
    Book book = new Book();
    book.Title = textBox1.Text;
    book.Author = db.Find(this.author.Id);

    db.Books.Add(book);
    db.SaveChanges();

    this.Close();
}

This will retrieve the author in the same context as the new book, and therefore will not create a new record.

Upvotes: 1

Related Questions