napfernandes
napfernandes

Reputation: 1359

Entity Framework - The property cannot be configured as a navigation property

I'm defining two entities like the following, but a strange behavior is occurring:

[Table("ClientTypes", Schema="dbo")]
public ClientType {
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
}

[Table("Clients", Schema="dbo")]
public Client {

    [Key]
    public long Id { get; set; }

    [ForeignKey("ClientTypeId")]
    public int ClientTypeId { get; set; }
    public virtual ClientType ClientType { get; set; }
}

I'm getting the ClientTypeId property filled with some value, but the ClientType object is filled with nothing. Can someone help me with this?

Thank you all!

Upvotes: 0

Views: 1331

Answers (3)

Evgeni Dimitrov
Evgeni Dimitrov

Reputation: 22506

When selecting the Client you have to Include the client type

Client cli = (from c in db Clients.Include("ClientType")//or the name of the property
              select c).First();

This translates to a left join and selects the data for Client and ClientType. If you skip the Include the EF will select the data only for the client when execute the statement. As Mike said if the context is still available the property will be lazy loaded when you access it.

Upvotes: 0

Wiseguy
Wiseguy

Reputation: 20883

The ForeignKey attribute as you have it is on the wrong property.

The annotation may be placed on the foreign key property and specify the associated navigation property name, or placed on a navigation property and specify the associated foreign key name.

- source

[ForeignKey("ClientTypeId")] should decorate public virtual ClientType ClientType instead,

or change it to [ForeignKey("ClientType")] and leave it where it is.

Upvotes: 2

Mike Cole
Mike Cole

Reputation: 14723

Are you eagerly loading the value?

var clients = context.Clients.Include("ClientType").ToList();

Upvotes: 0

Related Questions