向EntitySet添加实体抛出submitchanges上的异常()

时间:2010-09-02 14:22:45

标签: c# linq-to-sql

我正在使用Linq到Sql并且具有多对多关系,因此使用关系表。

当我尝试插入关系/关联数据时,我收到错误。

我使用手动架构创建。

我的简化代码:

第一个表/类Booklet有这个关联:

    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执行类似操作,则没有问题。

我做错了什么?我试图在自动模式生成的同一个数据库上做同样的事情,它工作正常。

谢谢,迈克尔。

2 个答案:

答案 0 :(得分:0)

  

ChapterID = 23

可能是问题所在。您的数据库是否允许您使用相同的章节创建BookletChapterRel?

BookletID是否在DB中自动增加?

答案 1 :(得分:0)

好的,我在检查了汽车设计师代码后解决了这个问题:

而不是使用:

private EntitySet<BookletChapterRel> _bookletChapterRel = new EntitySet<BookletChapterRel>();

我必须像这样使用EntitySet重载:

private EntitySet<BookletChapterRel> _bookletChapterRel;

构造

public Booklet()
{
   _bookletChapterRel = new EntitySet<BookletChapterRel>(new Action<BookletChapterRel>(this.attach_ep_book_chap_rels), null);
}