2

I have a model like this:

public class Entity
{
    [Key, Required]
    public virtual long EntityId { get; set; }
    [Required]
    public virtual string Name { get; set; }
    public virtual long? ParentEntityId { get; set; }
}

and this is my table:

create table Entities(
    EntityId bigint not null identity(1, 1),
    Name nvarchar(64) not null,
    ParentEntityId bigint null
)

ParentEntityId is a foreign key to EntityId.

When I try to create a Entity entity this is the exception I get: Invalid column name 'ParentEntity_EntityId'.

I don't know why EF is picking that convention for that particular column, but if I do this:

[Column("TryPickThisName")]
public virtual int? ParentEntityId { get; set; }

The same error shows up with "TryPickThisName" column name. And finally if I write the column name correctly or remove the attribute it will show the original error message.

1 Answer 1

5

Did you leave part of your model out?

I think what is happening is you're wanting to create a self referencing table, with Entity optionally referring to itself if it has a ParentEntity.

What's happening is EF is creating the ParentEntity_EntityId because you didn't explicitly map the FK property to the navigation property. Adding a ForeignKey data annotation will correct this.

public class Entity
{
    [Key, Required]
    public virtual long EntityId { get; set; }
    [Required]
    public virtual string Name { get; set; }

    [ForeignKey("ParentEntity")]
    public virtual long? ParentEntityId { get; set; }
    public virtual Entity ParentEntity { get; set; }
}

Creates this database: enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your response. I've added the attribute and it works.
My understanding was that the virtual keyword was for the entity and lazy loading. I notice it is on the key here, perhaps unnecessarily? Some purpose I'm not aware of, obviously.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.