2

ドキュメントのテーブルがあります:

public class Document
{
[Key]
public int DocumentId {get; set;}
public string Title {get; set;}
}

DepthDocuments のテーブルもあります。

public class DepthDocument
{
[Key]
public int DepthDocumentId {get; set;}
public int DocumentId {get; set;}
public int Depth {get; set;}
}

すべての Document には、対応する DepthDocument があります。両方のテーブルの行数は同じです。ドキュメントを削除するときに、対応するDepthDocumentも削除したいということをEFに伝えようとしています。これの一部は、1 対 1 の関係を作成していると思います。これを Document クラスに追加してみました。

    [Required]
    public virtual DepthDocument DepthDocument { get; set; }

そして、これ:

modelBuilder.Entity<Document>()
        .HasRequired(c => c.DepthDocument).WithRequiredPrincipal()
        .WillCascadeOnDelete(true);

しかし、私は得ています:

カスケード外部キー 'FK_dbo.DepthDocument_dbo.Document_DepthDocumentId' は、参照列 'DepthDocument.DepthDocumentId' が ID 列である場合に作成できません。

私は何を間違っていますか?

アップデート:

現在、DepthDocument テーブルを作成しているため、DocumentId 列と DepthDocumentId 列があり、シード メソッドで Document ごとに 1 つの新しい DepthDocument を作成する必要があります。

foreach (var document in context.Documents.ToList())
        {

            context.DepthDocuments.AddOrUpdate(
            d => d.DocumentId,
            new DepthDocument()
            {
                DocumentId = document.DocumentId, // can I do this?  I tried and ran into problems with missing entries not getting added
                // other props
            });
            context.SaveChanges();
        }
4

1 に答える 1

1

次のように変更DepthDocumentします。

public class DepthDocument
{
[Key]
public int DocumentId {get; set;}
public int Depth {get; set;}
}

これは 1 対 1 の関係でありDepthDocument、一致しないと存在できないため、別のキーを使用するDocument理由はありません。DepthDocument

于 2013-07-21T00:43:11.123 に答える