私はこれらのエンティティを持って、Entity Frameworkの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の仕事です。あなたのApplicationDbContext
クラスで
レコードがすでに存在するがかもしれません。 –
@AmitKumarGhoshいいえ、データベースが空です –
あなたのIDがGuidの場合、なぜ 'string'を使用するのですか?また、 'BookContext.BookPages.Add'を' BookPage'に、そして新しい 'Author'と同じようにしなければなりません。 – juharr