Я использую Linq to Sql и имею отношение «многие ко многим» и поэтому использую таблицу отношений.
Когда я пытаюсь вставить данные с отношением / ассоциацией, я получаю ошибку.
Я использую ручное создание схемы.
Мой упрощенный код:
Первая таблица / класс Буклет имеет такую связь:
private EntitySet<BookletChapterRel> _bookletChapterRel = new EntitySet<BookletChapterRel>();
[Association(Name = "ep_booklet_ep_book_chap_rel", OtherKey = "BookletID", ThisKey = "BookletID", Storage = "_bookletChapterRel")]
public EntitySet<BookletChapterRel> BookletChapterRel
{
set { _bookletChapterRel.Assign(value); }
get { return _bookletChapterRel; }
}
BookletChapterRel имеет следующие две ассоциации:
internal EntityRef<Booklet> _booklet;
[Association(Name = "ep_booklet_ep_book_chap_rel", OtherKey = "BookletID", ThisKey = "BookletID", Storage = "_booklet", IsForeignKey = true, DeleteOnNull = true, DeleteRule = "CASCADE")]
public Booklet Booklet
{
get { return _booklet.Entity; }
set { _booklet.Entity = value; BookletID = value.BookletID; }
}
internal EntityRef<Chapter> _chapter;
[Association(OtherKey = "ChapterID", ThisKey = "ChapterID", Storage = "_chapter")]
public Chapter Chapter
{
get { return _chapter.Entity; }
set { _chapter.Entity = value; ChapterID = value.ChapterID; }
}
Глава имеет следующую ассоциацию:
internal EntityRef<BookletChapterRel> _bookletChapterRel;
[Association(OtherKey = "ChapterID", ThisKey = "ChapterID", Storage = "_bookletChapterRel")]
public BookletChapterRel BookletChapterRel
{
get { return _bookletChapterRel.Entity; }
internal set { _bookletChapterRel.Entity = value; ChapterID = value.ChapterID; }
}
Я пытаюсь сделать простую вставку:
Booklet b = new Booklet();
b.NumberOfPages = 0;
b.Title = "Hello";
b.DateCreated = DateTime.Now;
b.DateModified = DateTime.Now;
bookletRepository.addBooklet(b); //Just calls booklettable.InsertOnSubmit()
var bookChapRel = new BookletChapterRel()
{
ChapterID = 23,
ViewOrder = 0
};
b.BookletChapterRel.Add(bookChapRel);
bookletRepository.SubmitBookletChanges();
Но каждый раз, когда я получаю исключение:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_ep_book_chap_rel_ep_booklet". The conflict occurred in database "easypiecy_v2", table "dbo.ep_booklet", column 'BookletID'.
Если я делаю что-то подобное с EntityRef, проблем нет.
Что я делаю не так?Я пытался сделать то же самое в той же базе данных с автоматической генерацией схемы, и она работала нормально.
Спасибо, Майкл.