Home > Enterprise >  Entity Framework one-to-many relationship not working
Entity Framework one-to-many relationship not working

Time:09-17

I started learning ASP.NET recently and now its the time for Entity Framework, but I'm having some troubles with the one-to-many relationship. I know there are the same questions already but I tried to follow the answers and I still couldn't make it work.

I have these two entities:

public class Map
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Place> Places { get; set; } = new List<Place>();
}

public class Place
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long Id { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public double Latitude { get; set; }
    public double Longitude { get; set; }
    public virtual Map Map { get; set; }
    public long MapId { get; set; }
}

and the relationship is defined like this:

protected override void OnModelCreating(ModelBuilder builder)
{
    builder.Entity<Place>()
        .HasOne(p => p.Map)
        .WithMany(m => m.Places)
        .HasForeignKey(p => p.MapId);
}

But no matter what I do, the collection Places is always empty:

var map = _dataContext.Maps
                      .Where(map => map.Id == id)
                      .Include(o => o.Places)
                      .SingleOrDefault();

I'm starting to losing my mind if someone could help me I'd appreciate.

Edit: sql migration output

CREATE TABLE IF NOT EXISTS "__EFMigrationsHistory" (
    "MigrationId" character varying(150) NOT NULL,
    "ProductVersion" character varying(32) NOT NULL,
    CONSTRAINT "PK___EFMigrationsHistory" PRIMARY KEY ("MigrationId")
);

START TRANSACTION;

CREATE TABLE "Maps" (
    "Id" bigint GENERATED BY DEFAULT AS IDENTITY,
    "Name" text NULL,
    CONSTRAINT "PK_Maps" PRIMARY KEY ("Id")
);

CREATE TABLE "Places" (
    "Id" bigint GENERATED BY DEFAULT AS IDENTITY,
    "Title" text NULL,
    "Description" text NULL,
    "Latitude" double precision NOT NULL,
    "Longitude" double precision NOT NULL,
    "MapId" bigint NOT NULL,
    CONSTRAINT "PK_Places" PRIMARY KEY ("Id"),
    CONSTRAINT "FK_Places_Maps_MapId" FOREIGN KEY ("MapId") REFERENCES "Maps" ("Id") ON DELETE CASCADE
);

CREATE INDEX "IX_Places_MapId" ON "Places" ("MapId");

INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")
VALUES ('20210909132715_init', '5.0.9');

COMMIT;

CodePudding user response:

Ok so I'm kinda dumb, after logging sql queries I saw that Include didn't work and realised that I had just one mistake, wrong import...

bad - using System.Data.Entity;

good - using Microsoft.EntityFrameworkCore;

I'm quite surprised that nothing complained about that import.

  • Related