我使用实体框架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