Esteban
Esteban

Reputation: 3139

Entity Framework: Code First - Column Mapping

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.

Upvotes: 2

Views: 2006

Answers (1)

Mark Oreta
Mark Oreta

Reputation: 10416

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

Upvotes: 5

Related Questions