1

I've been learning ADO.NET, and then EF Core. My assignment was to create a database application in C#, first in ADO.NET and then convert that app so it would use Entity Framework instead.

This was my design in ADO.NET, and it seemed to work fine.

CREATE TABLE Categories (
    Id INT IDENTITY,
    Name NVARCHAR(50) NOT NULL,
    CONSTRAINT PK_Categories
        PRIMARY KEY (Id)
)

CREATE TABLE CategoryCategories (
    ParentCategoryId INT,
    ChildCategoryId INT,
    CONSTRAINT PK_CategoryCategories
        PRIMARY KEY (ParentCategoryId, ChildCategoryId),
    CONSTRAINT FK_CategoryCategories_ParentCategoryId
        FOREIGN KEY (ParentCategoryId)
        REFERENCES Categories (Id),
    CONSTRAINT FK_CategoryCategories_ChildCategoryId
        FOREIGN KEY (ChildCategoryId)
        REFERENCES Categories (Id)
    ON DELETE CASCADE
)

CREATE TABLE Products (
    Id INT IDENTITY,
    ArticleNumber NVARCHAR(50) NOT NULL UNIQUE,
    Name NVARCHAR(50) NOT NULL,
    Description NVARCHAR(500) NOT NULL,
    Price DECIMAL(18,2) NOT NULL,
    CONSTRAINT PK_Products
        PRIMARY KEY (Id)
);

CREATE TABLE Products_Categories (
    ProductId INT,
    CategoryId INT NOT NULL,
    CONSTRAINT PK_Products_Categories
        PRIMARY KEY (ProductId, CategoryId),
    CONSTRAINT FK_ProdCats_Prods
        FOREIGN KEY (ProductId)
        REFERENCES Products (Id),
    CONSTRAINT FK_ProdCats_Cats
        FOREIGN KEY (CategoryId)
        REFERENCES Categories (Id)
    ON DELETE CASCADE
);

The connection between Products and Categories - no problem, just an ICollection property in each of the two responding classes. Entity Framework immediately created a CategoryProducts junction table.

When creating a connection between an entity and itself, that's where I ran into a wall. I tried simply copying all the model building code for CategoryProducts generated by the migrations into an OnModelCreating method for CategoryCategories, and inserting the right names of the columns and the tables.

Didn't work, got complaints that CategoryCategories was in shadow mode. I've vacuum-cleaned the internet trying to find a solution, but I can't find any clear instructions. Is it really so much harder to do this in Entity Framework than in regular SQL, or ADO.NET? I thought Entity Framework was supposed to make things easier.

Any suggestions? If you need more information, please let me know.

Edit

Thought I might add the classes, for clarity's sake.

    class Category
    {
        public int Id { get; protected set; }
        [Required]
        public string Name { get; protected set; }

        public ICollection<Product> Products { get; protected set; }
        // public ICollection<Category> ChildCategories { get; protected set; }
        public Category(string name)
        {
            Name = name;
            Products = new List<Product>();
            // ChildCategories = new List<Category>();
        }
    }

class CategoryCategory
    {
        // EFC forced me to have an Id. Could not run Add-migr Initial without it
        public int Id { get; protected set; }
        [Required]
        public int ParentCategoryId { get; protected set; }
        [Required]
        public int ChildCategoryId { get; protected set; }
        public CategoryCategory(int parentCategoryId, int childCategoryId)
        {
            ParentCategoryId = parentCategoryId;
            ChildCategoryId = childCategoryId;
        }
    }

    class Product
    {
        public int Id { get; protected set; }
        [Required]
        public string ArticleNumber { get; protected set; }
        [Required]
        // EFC forcing me to have unprotected set
        // Without it, I can not update articles :(
        public string Name { get; set; }
        [Required]
        public string Description { get; set; }
        [Required]
        public decimal Price { get; set; }

        public ICollection<Category> Categories { get; protected set; }

        public Product(string articleNumber, string name, string description, decimal price)
        {
            ArticleNumber = articleNumber;
            Name = name;
            Description = description;
            Price = price;
            Categories = new List<Category>();
        }

        public Product(int id, string articleNumber, string name, string description, decimal price)
            : this(articleNumber, name, description, price)
        {
            Id = id;
        }
    }

With these classes, EF says The entity type 'CategoryCategories' is in shadow state. A valid model requires all entity types to have corresponding CLR type.

If I uncomment the ICollection ChildCategories part in Category, then EF creates the third column, CategoryId in CategoryCategories, which is very undesirable in my opinion. Why should I want the third ID referring to Categories, when I already have two of them?

3
  • What is the purpose of a connection between an entity and itself? By the way, EF makes it much easier - as long as there is clarity in the requirements.
    – Felix
    Dec 12, 2020 at 8:25
  • The purpose was to create the above table CategoryCategories. Or rather, make EF create it. As I said, I want to replicate the ADO.NET design in EF, so the EF-tables will have exactly the same structure as the first (ADO.NET) ones.
    – theodorn
    Dec 12, 2020 at 8:30
  • As you can see, it has two foreign keys BOTH pointing go Categories.
    – theodorn
    Dec 12, 2020 at 8:31

1 Answer 1

1

The connection between Products and Categories - no problem, just an ICollection property in each of the two responding classes. Entity Framework immediately created a CategoryProducts junction table.

If this works, then you are using EF Core 5.0+ which added support for many-to-many relationship with implicit join entity, as can be seen, creating such relationship is quite easy.

But your CategoryCategories represents exactly the same type of relationship, with the only difference that both related ends are one and the same entity.

So how you create such relationship between two entities? You do that by adding 2(!) collection navigation properties in each related entity:

class Product
{
    public ICollection<Category> Categories { get; set; }
}

class Category
{
    public ICollection<Product> Products { get; set; }
}

(side note: the type of the property setter (public, internal, protected, private) doesn't matter for EF Core).

Which leads us to the answer of question how do you define such relationship between the same entity? Well, exactly the same - by adding 2(!) collection navigation properties in each related entity, which in this case is one and the same:

class Category
{
    public ICollection<Category> ParentCategories { get; set; }
    public ICollection<Category> ChildCategories { get; set; }
}

And that's it. No need of explicit CategoryCategory entity. EF Core creates automatically something like this

migrationBuilder.CreateTable(
    name: "CategoryCategory",
    columns: table => new
    {
        ChildCategoriesId = table.Column<int>(type: "int", nullable: false),
        ParentCategoriesId = table.Column<int>(type: "int", nullable: false)
    },
    constraints: table =>
    {
        table.PrimaryKey("PK_CategoryCategory", x => new { x.ChildCategoriesId, x.ParentCategoriesId });
        table.ForeignKey(
            name: "FK_CategoryCategory_Categories_ChildCategoriesId",
            column: x => x.ChildCategoriesId,
            principalTable: "Categories",
            principalColumn: "Id",
            onDelete: ReferentialAction.Cascade);
        table.ForeignKey(
            name: "FK_CategoryCategory_Categories_ParentCategoriesId",
            column: x => x.ParentCategoriesId,
            principalSchema: "SO14",
            principalTable: "Categories",
            principalColumn: "Id",
            onDelete: ReferentialAction.Restrict);
    });

If you don't like the generated table/column names, they are all configurable through fluent API. You can even create and map explicit join entity if you like, and still use the benefits of the so called "skip navigations".

But the two collection navigation properties are the bare minimum, and are the thing which makes the EF Core approach much easier.

1
  • Thanks a lot! I think this solved it. Don't know what I did wrong, which led to this extra CategoryId, but now everything seems to work fine, so that's moot. Thanks again.
    – theodorn
    Dec 12, 2020 at 11:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.