Home > Back-end >  C# Entity Framework LinkedList ForeignKeys
C# Entity Framework LinkedList ForeignKeys

Time:03-05

I want to save a LinkedList in the database to process later and therefor I´ve got a model which holds one field "Next" and one field "Previous". For the "create table" statement it should create two foreign keys named PreviousId and NextId but when I see the create statement in the SQLite Db there is only one.

I´ve added to the OnModelcreating Method the reference but it seems like the second is interpreted as dublicate of the first.

I´ve got the following model to store in the database:

public class BlockLink : BaseEntry
{
    [ForeignKey(nameof(PreviousId))]
    public ulong? PreviousId { get; set; }
    [ForeignKey(nameof(NextId))]
    public ulong? NextId { get; set; }

    public BlockLink Previous { get; set; }
    public int Current { get; set; }
    public BlockLink Next { get; set; }
    public Targets Target { get; set; }

    public BlockLink(Targets target) => Target = target;
}

And here the relation in the OnModelCreating Method:

            modelBuilder.Entity<BlockLink>()
           .HasOne(f => f.Next)
           .WithOne(f => f.Previous)
           .HasForeignKey(typeof(BlockLink), nameof(BlockLink.NextId));
        
        modelBuilder.Entity<BlockLink>()
           .HasOne(f => f.Previous)
           .WithOne(f => f.Next)
           .HasForeignKey(typeof(BlockLink), nameof(BlockLink.PreviousId));

This is the create statement:

CREATE TABLE "BlockList" (
"Id" INTEGER NOT NULL CONSTRAINT "PK_BlockList" PRIMARY KEY AUTOINCREMENT,
"PreviousId" INTEGER NULL,
"NextId" INTEGER NULL,
"Current" INTEGER NULL,
"Target" INTEGER NOT NULL,
"CreationTime" TEXT NOT NULL,
"LastUpdate" TEXT NOT NULL,
"Info" TEXT NULL,
CONSTRAINT "FK_BlockList_BlockList_PreviousId" FOREIGN KEY ("PreviousId") REFERENCES "BlockList" ("Id") ON DELETE RESTRICT)

CodePudding user response:

I´ve found out, that its not that much difficult. Solution:

modelBuilder.Entity<BlockLink>()
    .HasOne(x => x.Next);
modelBuilder.Entity<BlockLink>()
    .HasOne(n => n.Previous);

public class BlockLink : BaseEntry
{ 
    public ulong? PreviousId { get; set; }
    public ulong? NextId { get; set; }

    [ForeignKey(nameof(PreviousId))]
    public BlockLink Previous { get; set; }
    public TX_BASE_Type Current { get; set; }

    [ForeignKey(nameof(NextId))]
    public BlockLink Next { get; set; }
    public Targets Target { get; set; }

    public BlockLink(Targets target) => Target = target;
}
  • Related