简体   繁体   中英

How can I insert a row in my database that has a foreign key without adding a row in the linked table?

I created an Entity Model with Database First on my project. In my database i have two table´s. One for books and one for the author´s. The books have a foreign key on the authortable. And every time I want to add a new book, im adding a new author, even if the specified author already exists or I got an error.

This is are my classes:

Book

    public partial class BOOK
    {
        public int ID { get; set; }
        public string TITLE { get; set; }
        public int PAGENUMBER { get; set; }
        public int AUTHOR { get; set; }

        public virtual AUTHOR AUTHOR1 { get; set; }
    }

Author

    public partial class AUTHOR
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public AUTHOR()
        {
            this.BOOK = new HashSet<BOOK>();
        }

        public int ID { get; set; }
        public string FIRSTNAME{ get; set; }
        public string LASTNAME{ get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<BOOK> BOOK { get; set; }
    }

I have tried in several ways to just add the book and when I created it I specified the author or added the new book to the author's list. Most of the time it results in an error and the first time the author was added to the author table a second time. Maybe I'm missing something obvious or don't know a certain method because I'm an absolute beginner with the Entity Framework.

EDIT: I have always tried to get the author via a select query before and pass it to the book as an object.

var functions= new DbFunctions();
var author = functions.SelectAuthor(8); //Select with the ID

var book = new BOOK()
    {
        AUTHOR1 = author,
        TITLE= "ABC",
        PAGENUMBER = 30,
    };

    var context = new EF6_DbFirst_DatabaseEntities();
    context.BOOK.Add(book);
    context.SaveChanges();

That returns this error: System.InvalidOperationException: 'An entity object cannot be referenced by multiple instances of IEntityChangeTracker.'

I don't know much about Code First method, but if you want to reach your goal, you should know something about INNER JOINS in sql server.

I mean you should add a new row to your Books table which matches the key in Authors table, which we call Foreign key .

I hope this link could help you achieve what you want:

https://www.sqlservertutorial.net/sql-server-basics/sql-server-inner-join/

I found the simple answer. If I just give the author ID to AUTHOR while creating the book it works. I have missed this simple way again and again.

var functions= new DbFunctions();
var author = functions.SelectAuthor(8); //Select with the ID

var book = new BOOK()
    {
        AUTHOR = author.ID, //this simple Change will did it correct
        TITLE= "ABC",
        PAGENUMBER = 30,
    };

    var context = new EF6_DbFirst_DatabaseEntities();
    context.BOOK.Add(book);
    context.SaveChanges();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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