我使用實體框架7 RC1的,我有這些實體:INSERT語句衝突與實體框架的核心外鍵約束
public class Book
{
[Key]
public string BookId { get; set; }
public List<BookPage> Pages { get; set; }
public Author Author { get; set; }
public string Text { get; set; }
}
public class BookPage
{
[Key]
public string BookPageId { get; set; }
public int Number { get; set; }
}
public class Author
{
[Key]
public string AuthorId { get; set; }
public string FullName { get; set; }
}
ApplicationDbContext.cs是默認情況下,public DbSet<Book> Books { get; set; }
當我試圖插入新的圖書,這樣
var book = new Book()
{
BookId = Guid.NewGuid().ToString(),
Pages = new List<BookPage>()
{
new BookPage()
{
BookPageId = Guid.NewGuid().ToString(),
Number = 1
}
},
Author = new Author()
{
AuthorId = Guid.NewGuid().ToString(),
FullName = "Forexample"
},
Text = "new book"
};
dbContext.Books.Add(book);
dbContext.SaveChanges();
它拋出異常:
SqlException:INSERT語句與FOREIGN KEY約束「FK_Book_Author_AuthorAuthorId」衝突。
這個簡單的插入有什麼問題?我不想手動添加BookPage和Author,它是Entity Framework作業。
記錄已經存在的可能。 –
@AmitKumarGhosh不,數據庫爲空 –
如果你的id是Guids,爲什麼使用'string'?另外,我非常肯定你必須'dbContext.BookPages.Add'這個'BookPage',並且和新的'Author'一樣。 – juharr